#include "appname.h"
#include "upgrade.h"
-AboutDlg::AboutDlg(QWidget *parent, const QString &ver1,
- const QString &ver2, const QString& installationId): QDialog(parent)
+AboutDlg::AboutDlg(QWidget* parent, const QString& ver1,
+ const QString& ver2, const QString& installationId): QDialog(parent)
{
ui_.setupUi(this);
- QTextDocument *doc = ui_.textEdit->document();
+ QTextDocument* doc = ui_.textEdit->document();
ui_.textEdit->setReadOnly(true);
QString tt = doc->toHtml();
tt.replace(QRegExp("\\$appname\\$"), QString(appName));
tt.replace(QRegExp("\\$installationId\\$"), installationId);
// Not localized as it should never be seen.
- tt.replace(QRegExp("\\$upgradetestmode\\$"),
- UpgradeCheck::isTestMode() ? "**Upgrade test mode**" : "");
-
+ tt.replace(QRegExp("\\$upgradetestmode\\$"),
+ UpgradeCheck::isTestMode() ? "**Upgrade test mode**" : "");
+
doc->setHtml(tt);
QTextCursor cur(doc);
cur.setPosition(0);
#include "ui_aboutui.h"
-class AboutDlg: public QDialog {
- public:
- AboutDlg(QWidget *parent, const QString &ver1,
- const QString &ver2, const QString &installationId);
+class AboutDlg: public QDialog
+{
+public:
+ AboutDlg(QWidget* parent, const QString& ver1,
+ const QString& ver2, const QString& installationId);
- private:
+private:
Ui_AboutDlg ui_;
};
//------------------------------------------------------------------------
AdvDlg::AdvDlg(QWidget* parent,
- bool &synthShortNames,
- bool &previewGmap,
- int &debugLevel):
+ bool& synthShortNames,
+ bool& previewGmap,
+ int& debugLevel):
QDialog(parent),
synthShortNames_(synthShortNames),
previewGmap_(previewGmap),
#include "ui_advui.h"
-class AdvDlg: public QDialog {
+class AdvDlg: public QDialog
+{
Q_OBJECT
-
+
public:
- AdvDlg(QWidget* parent,
- bool &synthShortNames_,
- bool &previewGmap_,
- int &debugLevel_);
- QPushButton* formatButton() { return ui_.formatButton; };
+ AdvDlg(QWidget* parent,
+ bool& synthShortNames_,
+ bool& previewGmap_,
+ int& debugLevel_);
+ QPushButton* formatButton()
+ {
+ return ui_.formatButton;
+ };
private:
Ui_AdvUi ui_;
- bool &synthShortNames_;
- bool &previewGmap_;
- int &debugLevel_;
+ bool& synthShortNames_;
+ bool& previewGmap_;
+ int& debugLevel_;
- protected:
+protected:
- private slots:
+private slots:
void acceptClicked();
void rejectClicked();
};
//
#ifndef APPNAME_H
#define APPNAME_H
-static const char *appName = "GPSBabel";
+static const char* appName = "GPSBabel";
#endif
#include "setting.h"
-class BabelData {
+class BabelData
+{
public:
- BabelData():
+ BabelData():
inputType_(fileType_),
inputFileFormat_(QString()),
inputDeviceFormat_(QString()),
donateSplashed_(QDateTime(QDate(2010, 1, 1), QTime(0, 0, 0)))
{
};
-
- void saveSettings(QSettings &st) {
+
+ void saveSettings(QSettings& st)
+ {
SettingGroup sg;
makeSettingGroup(sg);
sg.saveSettings(st);
}
- void restoreSettings(QSettings &st) {
+ void restoreSettings(QSettings& st)
+ {
SettingGroup sg;
makeSettingGroup(sg);
sg.restoreSettings(st);
}
- void makeSettingGroup(SettingGroup &sg) {
+ void makeSettingGroup(SettingGroup& sg)
+ {
sg.addVarSetting(new IntSetting("app.inputType", inputType_));
sg.addVarSetting(new StringSetting("app.inputFileFormat", inputFileFormat_));
sg.addVarSetting(new StringSetting("app.inputDeviceFormat", inputDeviceFormat_));
bool xlateWayPts_;
bool xlateRoutes_;
bool xlateTracks_;
-
+
int outputType_;
QString outputFileFormat_;
QString outputDeviceFormat_;
#include <QDesktopServices>
// A completely simple QDialog, in a class of its own for layout.
-Donate::Donate(QWidget *parent) : QDialog(parent)
+Donate::Donate(QWidget* parent) : QDialog(parent)
{
ui_.setupUi(this);
connect(ui_.contributeButton, SIGNAL(clicked()), this, SLOT(contributeClicked()));
#include "ui_donate.h"
-class Donate: public QDialog {
- Q_OBJECT
-
- public:
- Donate(QWidget *parent);
- void showNever(bool f) {
+class Donate: public QDialog
+{
+ Q_OBJECT
+
+public:
+ Donate(QWidget* parent);
+ void showNever(bool f)
+ {
ui_.neverAgain->setVisible(f);
ui_.textLine2->setVisible(f);
}
- bool neverAgain() { return ui_.neverAgain->isChecked(); }
+ bool neverAgain()
+ {
+ return ui_.neverAgain->isChecked();
+ }
- private:
+private:
Ui_Donate ui_;
- private slots:
+private slots:
void contributeClicked();
};
// $Id: dpencode.cpp,v 1.3 2009-09-08 16:06:32 robertl Exp $
//------------------------------------------------------------------------
//
-// Original in JavaScript:
+// Original in JavaScript:
// PolylineEncoder.js copyright Mark McClure April/May 2007
//
// Translated to C++
PolylineEncoder::PolylineEncoder(int numLevels, double zoomFactor, double vs):
numLevels(numLevels), verySmall(vs)
{
- if (verySmall <=0.0)
+ if (verySmall <=0.0) {
verySmall = 1.0E-5;
- for(int i = 0; i < numLevels; i++)
+ }
+ for (int i = 0; i < numLevels; i++) {
zoomLevelBreaks.push_back(verySmall*pow(zoomFactor, numLevels-i-1));
+ }
}
//------------------------------------------------------------------------
class IntervalPair
{
public:
- IntervalPair(int i0, int i1): i0(i0), i1(i1) {
+ IntervalPair(int i0, int i1): i0(i0), i1(i1)
+ {
}
int i0, i1;
};
//------------------------------------------------------------------------
-static double hypotenuse(double a, double b){
+static double hypotenuse(double a, double b)
+{
return sqrt(a*a + b*b);
}
//------------------------------------------------------------------------
-static double hdist(const LatLng &a, const LatLng &b) {
+static double hdist(const LatLng& a, const LatLng& b)
+{
return hypotenuse(a.lat()-b.lat(), a.lng()-b.lng());
}
//------------------------------------------------------------------------
-static string encodeNumber(int num)
+static string encodeNumber(int num)
{
string encodeString = "";
while (num >= 0x20) {
//------------------------------------------------------------------------
// This one is Google's verbatim.
-static string encodeSignedNumber (int num)
+static string encodeSignedNumber(int num)
{
int sgn_num = num << 1;
if (num < 0) {
sgn_num = ~(sgn_num);
}
- return(encodeNumber(sgn_num));
+ return (encodeNumber(sgn_num));
}
//------------------------------------------------------------------------
-int roundToInt(double x) {
+int roundToInt(double x)
+{
return (x>0.0) ? int(x+0.5) : int(x-0.5);
}
//------------------------------------------------------------------------
-void PolylineEncoder::createEncodings(string &encoded_points,
- const vector <LatLng> &points,
- const vector <double> &dists)
+void PolylineEncoder::createEncodings(string& encoded_points,
+ const vector <LatLng>& points,
+ const vector <double>& dists)
{
encoded_points = "";;
int plat = 0;
int plng = 0;
- for(unsigned int i = 0; i < points.size(); i++) {
- if(dists[i] >= 0.0 || i == 0 || i == points.size()-1) {
+ for (unsigned int i = 0; i < points.size(); i++) {
+ if (dists[i] >= 0.0 || i == 0 || i == points.size()-1) {
int late5 = roundToInt(points[i].lat() * 1e5);
int lnge5 = roundToInt(points[i].lng() * 1e5);
int dlat = late5 - plat;
int PolylineEncoder::computeLevel(double dd)
{
int lev = 0;
- if(dd > verySmall) {
- while(dd < zoomLevelBreaks[lev]) {
+ if (dd > verySmall) {
+ while (dd < zoomLevelBreaks[lev]) {
lev++;
}
}
// Now we can use the previous function to march down the list
// of points and encode the levels. Like createEncodings, we
// ignore points whose distance (in dists) is undefined.
-void PolylineEncoder::encodeLevels(string &encoded_levels, const vector<LatLng> &points, const vector<double>&dists)
+void PolylineEncoder::encodeLevels(string& encoded_levels, const vector<LatLng>& points, const vector<double>& dists)
{
encoded_levels = "";
encoded_levels += encodeNumber(numLevels-1);
for (unsigned int i=1; i<points.size()-1; i++) {
- if(dists[i] >= 0.0) {
+ if (dists[i] >= 0.0) {
encoded_levels += encodeNumber(numLevels-computeLevel(dists[i])-1);
}
}
//------------------------------------------------------------------------
-double PolylineEncoder::distance(const LatLng &p0, const LatLng &p1, const LatLng &p2)
+double PolylineEncoder::distance(const LatLng& p0, const LatLng& p1, const LatLng& p2)
{
double out = 0.0;
if (p1.lat() == p2.lat() && p1.lng() == p2.lng()) {
out = hdist(p2, p0);
- }
- else {
+ } else {
double dlat = (p2.lat()-p1.lat());
double dlng = (p2.lng()-p1.lng());
double u = ((p0.lat()-p1.lat())*dlat+(p0.lng()-p1.lng())*dlng)/(dlat*dlat + dlng*dlng);
-
+
if (u <= 0) {
out = hdist(p0, p1);
- }
- else if(u >= 1) {
+ } else if (u >= 1) {
out = hdist(p0, p2);
- }
- else {
+ } else {
out = hdist(p0, LatLng(p1.lat() + u*dlat, p1.lng() + u*dlng));
}
}
}
//------------------------------------------------------------------------
-void PolylineEncoder::dpEncode(string &encPts, string &encLevels, const vector<LatLng> &points)
+void PolylineEncoder::dpEncode(string& encPts, string& encLevels, const vector<LatLng>& points)
{
if (points.size() < 2) {
encPts = encLevels = ""; // no solution here.
}
stack <IntervalPair> stk;
vector <double> dists(points.size(), -1.0);
-
+
stk.push(IntervalPair(0, int(points.size())-1));
while (!stk.empty()) {
-
+
IntervalPair current = stk.top();
stk.pop();
-
+
double maxDist = -1.0;
int maxLoc = -1;
for (int i=current.i0+1; i<current.i1; i++) {
double dist = this->distance(points[i], points[current.i0], points[current.i1]);
- if(dist > maxDist) {
- maxDist = dist;
- maxLoc = i;
+ if (dist > maxDist) {
+ maxDist = dist;
+ maxLoc = i;
}
}
- if(maxDist > this->verySmall) {
+ if (maxDist > this->verySmall) {
dists[maxLoc] = maxDist;
stk.push(IntervalPair(current.i0, maxLoc));
stk.push(IntervalPair(maxLoc, current.i1));
using std::string;
-class PolylineEncoder {
+class PolylineEncoder
+{
public:
PolylineEncoder(int numLevels=19, double zoomFactor=2.0, double verySmall = 0.00001);
- void dpEncode(string &encPts, string &encLevels, const vector<LatLng> &points);
-
+ void dpEncode(string& encPts, string& encLevels, const vector<LatLng>& points);
+
private:
int computeLevel(double dd);
- double distance(const LatLng &, const LatLng &, const LatLng &);
- void encodeLevels(string &, const vector<LatLng> &points, const vector<double>&dists);
- void createEncodings(string &encoded_points,
- const vector <LatLng> &points,
- const vector <double> &dists);
+ double distance(const LatLng&, const LatLng&, const LatLng&);
+ void encodeLevels(string&, const vector<LatLng>& points, const vector<double>& dists);
+ void createEncodings(string& encoded_points,
+ const vector <LatLng>& points,
+ const vector <double>& dists);
int numLevels;
double verySmall;
QStringList WayPtsFilterData::makeOptionString()
{
QStringList args;
- if (!inUse_)
+ if (!inUse_) {
return args;
+ }
if (radius) {
args << QString("-x");
args << QString("radius,distance=%1%2,lat=%3,lon=%4")
- .arg(radiusVal).arg("MK"[radiusUnit]).arg(latVal, 0, 'f', 8).arg(longVal, 0, 'f', 8);
+ .arg(radiusVal).arg("MK"[radiusUnit]).arg(latVal, 0, 'f', 8).arg(longVal, 0, 'f', 8);
}
if (duplicates && (shortNames ^ locations)) {
args << QString("-x");
QString s = "duplicate";
- if (shortNames)
+ if (shortNames) {
s += ",shortname";
- if (locations)
+ }
+ if (locations) {
s += ",location";
+ }
args << s;
}
}
//------------------------------------------------------------------------
-static QString optionDate(const QDateTime &dt, bool useLocal)
+static QString optionDate(const QDateTime& dt, bool useLocal)
{
QDateTime d;
if (useLocal) {
d = dt.toLocalTime();
- }
- else {
+ } else {
d = dt.toUTC();
}
QDate date = d.date();
QTime time = d.time();
QString s = QString("%1%2%3%4%5%6")
- .arg(date.year(), 4, 10, QChar('0'))
- .arg(date.month(), 2, 10, QChar('0'))
- .arg(date.day(), 2, 10, QChar('0'))
- .arg(time.hour(), 2, 10, QChar('0'))
- .arg(time.minute(), 2, 10, QChar('0'))
- .arg(time.second(), 2, 10, QChar('0'));
+ .arg(date.year(), 4, 10, QChar('0'))
+ .arg(date.month(), 2, 10, QChar('0'))
+ .arg(date.day(), 2, 10, QChar('0'))
+ .arg(time.hour(), 2, 10, QChar('0'))
+ .arg(time.minute(), 2, 10, QChar('0'))
+ .arg(time.second(), 2, 10, QChar('0'));
return s;
}
//------------------------------------------------------------------------
QStringList TrackFilterData::makeOptionString()
{
- static const char *fixStrings[] = {"none", "pps", "dgpss", "3d", "2d"}; // match with designer!
+ static const char* fixStrings[] = {"none", "pps", "dgpss", "3d", "2d"}; // match with designer!
QStringList args;
- if (!inUse_)
+ if (!inUse_) {
return args;
+ }
QString s;
- if (GPSFixes) s += QString(",fix=%1").arg(fixStrings[GPSFixesVal]);
- if (course) s += ",course";
- if (speed) s += ",speed";
- if (pack) s += ",pack";
- if (merge) s += ",merge";
+ if (GPSFixes) {
+ s += QString(",fix=%1").arg(fixStrings[GPSFixesVal]);
+ }
+ if (course) {
+ s += ",course";
+ }
+ if (speed) {
+ s += ",speed";
+ }
+ if (pack) {
+ s += ",pack";
+ }
+ if (merge) {
+ s += ",merge";
+ }
if (pack || merge) {
if (splitByDate) {
s += ",split";
}
if (splitByTime) {
s += ",split";
- if (splitTime > 0)
- s += QString("=%1%2").arg(splitTime).arg("mhd"[splitTimeUnit]);
+ if (splitTime > 0) {
+ s += QString("=%1%2").arg(splitTime).arg("mhd"[splitTimeUnit]);
+ }
}
if (splitByDistance && splitDist > 0) {
double d = splitDist;
char u = ' ';
if (splitDistUnit == 0) { // ft.
- d /= 5280.0; u = 'm';
- }
- else if (splitDistUnit == 1) { //m
- d /= 1000.0; u = 'k';
- }
- else if (splitDistUnit == 2) { //km
- u = 'k';
- }
- else if (splitDistUnit == 3) { //m
- u = 'm';
+ d /= 5280.0;
+ u = 'm';
+ } else if (splitDistUnit == 1) { //m
+ d /= 1000.0;
+ u = 'k';
+ } else if (splitDistUnit == 2) { //km
+ u = 'k';
+ } else if (splitDistUnit == 3) { //m
+ u = 'm';
}
s += QString(",sdistance=%1%2").arg(d).arg(u);
}
}
- if (start) s += QString(",start=%1").arg(optionDate(startTime, TZ));
- if (stop) s += QString(",stop=%1").arg(optionDate(stopTime, TZ));
- if (move) s += QString(",move=%1d%2h%3m%4s").arg(days).arg(hours).arg(mins).arg(secs);
- if (title) s += QString(",title=%1").arg(titleString);
+ if (start) {
+ s += QString(",start=%1").arg(optionDate(startTime, TZ));
+ }
+ if (stop) {
+ s += QString(",stop=%1").arg(optionDate(stopTime, TZ));
+ }
+ if (move) {
+ s += QString(",move=%1d%2h%3m%4s").arg(days).arg(hours).arg(mins).arg(secs);
+ }
+ if (title) {
+ s += QString(",title=%1").arg(titleString);
+ }
- if (s.length())
+ if (s.length()) {
args << "-x" << "track" + s;
+ }
return args;
}
QStringList RtTrkFilterData::makeOptionString()
{
QStringList args;
- if (!inUse_)
+ if (!inUse_) {
return args;
+ }
- if (reverse_) args << QString("-x") << QString("reverse");
- if (simplify_) args << QString("-x") << QString("simplify,count=%1").arg(limitTo_);
+ if (reverse_) {
+ args << QString("-x") << QString("reverse");
+ }
+ if (simplify_) {
+ args << QString("-x") << QString("simplify,count=%1").arg(limitTo_);
+ }
return args;
}
QStringList MiscFltFilterData::makeOptionString()
{
QStringList args;
- if (!inUse_)
+ if (!inUse_) {
return args;
+ }
if (nukeRoutes_ || nukeTracks_ || nukeWaypoints_) {
args << QString("-x");
QString s = "nuketypes";
- if (nukeRoutes_) s += ",routes";
- if (nukeTracks_) s += ",tracks";
- if (nukeWaypoints_) s += ",waypoints";
+ if (nukeRoutes_) {
+ s += ",routes";
+ }
+ if (nukeTracks_) {
+ s += ",tracks";
+ }
+ if (nukeWaypoints_) {
+ s += ",waypoints";
+ }
args << s;
}
- if (swap_) args << "-x" << "swap";
+ if (swap_) {
+ args << "-x" << "swap";
+ }
if (transform_) {
- static const char *xformStr[] = {
+ static const char* xformStr[] = {
"wpt=trk",
"trk=rte",
"rte=wpt",
};
args << QString("-x");
QString s= QString("transform,%1").arg(xformStr[transformVal_]);
- if (del_) s += ",del";
+ if (del_) {
+ s += ",del";
+ }
args << s;
}
return args;
//------------------------------------------------------------------------
-class FilterData {
+class FilterData
+{
public:
FilterData(): inUse_(true) {};
virtual ~FilterData() {};
- void saveSettings(QSettings &st) {
+ void saveSettings(QSettings& st)
+ {
SettingGroup sg;
makeSettingGroup(sg);
sg.saveSettings(st);
}
- void restoreSettings(QSettings &st) {
+ void restoreSettings(QSettings& st)
+ {
SettingGroup sg;
makeSettingGroup(sg);
sg.restoreSettings(st);
}
- virtual void makeSettingGroup(SettingGroup &sg) = 0;
+ virtual void makeSettingGroup(SettingGroup& sg) = 0;
virtual QStringList makeOptionString() = 0;
public:
};
//------------------------------------------------------------------------
-class TrackFilterData: public FilterData {
- public:
+class TrackFilterData: public FilterData
+{
+public:
TrackFilterData(): FilterData(), title(false), titleString(QString()),
- move(false), days(0), hours(0), mins(0), secs(0),
- TZ(false),
- start(false),
- stop(false),
- pack(false), merge(false), split(false),
- GPSFixes(false), GPSFixesVal(0),
- splitByDate(false),
- splitByTime(false),
- splitByDistance(false),
- course(false), speed(false),
- splitTime(0), splitTimeUnit(0),
- splitDist(0), splitDistUnit(0)
+ move(false), days(0), hours(0), mins(0), secs(0),
+ TZ(false),
+ start(false),
+ stop(false),
+ pack(false), merge(false), split(false),
+ GPSFixes(false), GPSFixesVal(0),
+ splitByDate(false),
+ splitByTime(false),
+ splitByDistance(false),
+ course(false), speed(false),
+ splitTime(0), splitTimeUnit(0),
+ splitDist(0), splitDistUnit(0)
{
titleString = "ACTIVE LOG #%Y%m%d";
stopTime = QDateTime::currentDateTime();
startTime = stopTime.addMonths(-6);
startTime.setTime(QTime(0, 0, 1));
}
- virtual void makeSettingGroup(SettingGroup &sg)
+ virtual void makeSettingGroup(SettingGroup& sg)
{
sg.addVarSetting(new BoolSetting("trks.inUse", inUse_));
sg.addVarSetting(new BoolSetting("trks.GPSFixes", GPSFixes));
sg.addVarSetting(new IntSetting("trks.splitDistUnit", splitDistUnit));
}
virtual QStringList makeOptionString();
-
- public:
+
+public:
bool title;
QString titleString;
bool move;
//------------------------------------------------------------------------
-class WayPtsFilterData: public FilterData {
- public:
- WayPtsFilterData(): FilterData(),
- duplicates(false), shortNames(true), locations(false),
- position(false), radius(false), sort(false),
- positionVal(0.0), radiusVal(0.0),
- longVal(0.0), latVal(0.0),
- positionUnit(0), radiusUnit(0)
- {
- }
-
+class WayPtsFilterData: public FilterData
+{
+public:
+ WayPtsFilterData(): FilterData(),
+ duplicates(false), shortNames(true), locations(false),
+ position(false), radius(false), sort(false),
+ positionVal(0.0), radiusVal(0.0),
+ longVal(0.0), latVal(0.0),
+ positionUnit(0), radiusUnit(0)
+ {
+ }
+
virtual QStringList makeOptionString();
- virtual void makeSettingGroup(SettingGroup &sg)
+ virtual void makeSettingGroup(SettingGroup& sg)
{
sg.addVarSetting(new BoolSetting("wpts.inUse", inUse_));
sg.addVarSetting(new BoolSetting("wpts.radius", radius));
}
- public:
+public:
bool duplicates, shortNames, locations, position, radius, sort;
double positionVal;
double radiusVal;
};
//------------------------------------------------------------------------
-class RtTrkFilterData: public FilterData {
- public:
- RtTrkFilterData(): FilterData(),
- simplify_(false),
- reverse_(false),
- limitTo_(100)
- {
- }
-
+class RtTrkFilterData: public FilterData
+{
+public:
+ RtTrkFilterData(): FilterData(),
+ simplify_(false),
+ reverse_(false),
+ limitTo_(100)
+ {
+ }
+
virtual QStringList makeOptionString();
- virtual void makeSettingGroup(SettingGroup &sg) {
+ virtual void makeSettingGroup(SettingGroup& sg)
+ {
sg.addVarSetting(new BoolSetting("rttrk.inUse", inUse_));
sg.addVarSetting(new BoolSetting("rttrk.reverse", reverse_));
sg.addVarSetting(new BoolSetting("rttrk.simplify", simplify_));
sg.addVarSetting(new IntSetting("rttrk.limitTo", limitTo_));
}
- public:
+public:
bool simplify_, reverse_;
int limitTo_;
};
//------------------------------------------------------------------------
-class MiscFltFilterData: public FilterData {
- public:
- MiscFltFilterData(): FilterData(),
- nukeRoutes_(false),
- nukeTracks_(false),
- nukeWaypoints_(false),
- transform_(false),
- del_(false),
- swap_(false),
- transformVal_(0)
- {
- }
-
+class MiscFltFilterData: public FilterData
+{
+public:
+ MiscFltFilterData(): FilterData(),
+ nukeRoutes_(false),
+ nukeTracks_(false),
+ nukeWaypoints_(false),
+ transform_(false),
+ del_(false),
+ swap_(false),
+ transformVal_(0)
+ {
+ }
+
virtual QStringList makeOptionString();
- virtual void makeSettingGroup(SettingGroup &sg)
+ virtual void makeSettingGroup(SettingGroup& sg)
{
sg.addVarSetting(new BoolSetting("mscflt.nukeRoutes", nukeRoutes_));
sg.addVarSetting(new BoolSetting("mscflt.nukeTracks", nukeTracks_));
sg.addVarSetting(new BoolSetting("mscflt.swap", swap_));
}
- public:
+public:
bool nukeRoutes_, nukeTracks_, nukeWaypoints_;
bool transform_, del_, swap_;
int transformVal_;
//
class AllFiltersData
{
- public:
+public:
AllFiltersData()
{
defaultAll();
filters << &wayPtsFilterData;
filters << &rtTrkFilterData;
}
-
- void defaultAll() {
+
+ void defaultAll()
+ {
miscFltFilterData = MiscFltFilterData();
trackFilterData = TrackFilterData();
wayPtsFilterData = WayPtsFilterData();
rtTrkFilterData = RtTrkFilterData();
}
- QStringList getAllFilterStrings() {
+ QStringList getAllFilterStrings()
+ {
QStringList args;
- for (int i=0; i<filters.size(); i++)
+ for (int i=0; i<filters.size(); i++) {
args << filters[i]->makeOptionString();
+ }
return args;
}
WayPtsFilterData wayPtsFilterData;
RtTrkFilterData rtTrkFilterData;
MiscFltFilterData miscFltFilterData;
- QList<FilterData *>filters;
+ QList<FilterData*>filters;
};
int FilterDialog::lastPage_ = 0;
-FilterDialog::FilterDialog(QWidget*parent, AllFiltersData &fd): QDialog(parent), fd_(fd)
+FilterDialog::FilterDialog(QWidget* parent, AllFiltersData& fd): QDialog(parent), fd_(fd)
{
ui_.setupUi(this);
ui_.filterList->clear();
widgetStack_ = new QStackedWidget(ui_.frame);
- QHBoxLayout *layout = new QHBoxLayout(ui_.frame);
+ QHBoxLayout* layout = new QHBoxLayout(ui_.frame);
layout->addWidget(widgetStack_);
layout->setContentsMargins(2, 2, 2, 2);
addFilterPage(tr("Tracks"),
- new TrackWidget(widgetStack_, fd.trackFilterData), &fd.trackFilterData.inUse_);
+ new TrackWidget(widgetStack_, fd.trackFilterData), &fd.trackFilterData.inUse_);
addFilterPage(tr("Waypoints"),
- new WayPtsWidget(widgetStack_, fd.wayPtsFilterData), &fd.wayPtsFilterData.inUse_);
+ new WayPtsWidget(widgetStack_, fd.wayPtsFilterData), &fd.wayPtsFilterData.inUse_);
addFilterPage(tr("Routes & Tracks"),
- new RtTrkWidget(widgetStack_, fd.rtTrkFilterData), &fd.rtTrkFilterData.inUse_);
+ new RtTrkWidget(widgetStack_, fd.rtTrkFilterData), &fd.rtTrkFilterData.inUse_);
addFilterPage(tr("Miscellaneous"),
- new MiscFltWidget(widgetStack_, fd.miscFltFilterData), &fd.miscFltFilterData.inUse_);
+ new MiscFltWidget(widgetStack_, fd.miscFltFilterData), &fd.miscFltFilterData.inUse_);
connect(ui_.filterList, SIGNAL(currentRowChanged(int)),
- this, SLOT(pageSelectionChanged(int)));
+ this, SLOT(pageSelectionChanged(int)));
- connect(ui_.filterList, SIGNAL(itemClicked(QListWidgetItem *)),
- this, SLOT(itemClickedX(QListWidgetItem*)));
+ connect(ui_.filterList, SIGNAL(itemClicked(QListWidgetItem*)),
+ this, SLOT(itemClickedX(QListWidgetItem*)));
connect(ui_.helpButton, SIGNAL(clicked()), this, SLOT(helpX()));
connect(ui_.resetButton, SIGNAL(clicked()), this, SLOT(resetX()));
//------------------------------------------------------------------------
-void FilterDialog::addFilterPage(const QString &name, FilterWidget *fw, bool*use)
+void FilterDialog::addFilterPage(const QString& name, FilterWidget* fw, bool* use)
{
- QListWidgetItem *it = new QListWidgetItem(name);
+ QListWidgetItem* it = new QListWidgetItem(name);
it->setCheckState(*use? Qt::Checked:Qt::Unchecked);
fw->setEnabled(*use);
ui_.filterList->addItem(it);
}
//------------------------------------------------------------------------
-void FilterDialog::itemClickedX(QListWidgetItem *it)
+void FilterDialog::itemClickedX(QListWidgetItem* it)
{
int row = ui_.filterList->row(it);
bool b = (it->checkState() == Qt::Checked);
void FilterDialog::resetX()
{
int ret = QMessageBox::warning
- (this, QString(appName),
- tr("Are you sure you want to reset all filter options to default values?"),
- QMessageBox::Yes | QMessageBox::No);
+ (this, QString(appName),
+ tr("Are you sure you want to reset all filter options to default values?"),
+ QMessageBox::Yes | QMessageBox::No);
if (ret == QMessageBox::Yes) {
fd_.defaultAll();
class FilterDialog: public QDialog
{
-Q_OBJECT
- public:
- FilterDialog(QWidget *parent, AllFiltersData &fd_);
+ Q_OBJECT
+public:
+ FilterDialog(QWidget* parent, AllFiltersData& fd_);
~FilterDialog() {}
void runDialog();
-
- private:
+
+private:
static int lastPage_;
- QList <FilterWidget *>pages_;
- QList <bool *>usePages_;
- QStackedWidget *widgetStack_;
+ QList <FilterWidget*>pages_;
+ QList <bool*>usePages_;
+ QStackedWidget* widgetStack_;
Ui_FilterDlg ui_;
- AllFiltersData &fd_;
+ AllFiltersData& fd_;
- void addFilterPage(const QString & name, FilterWidget *w, bool *);
+ void addFilterPage(const QString& name, FilterWidget* w, bool*);
private slots:
void pageSelectionChanged(int);
- void itemClickedX(QListWidgetItem *);
+ void itemClickedX(QListWidgetItem*);
void resetX();
void helpX();
};
//------------------------------------------------------------------------
-TrackWidget::TrackWidget(QWidget *parent, TrackFilterData &tfd): FilterWidget(parent) , tfd(tfd)
+TrackWidget::TrackWidget(QWidget* parent, TrackFilterData& tfd): FilterWidget(parent), tfd(tfd)
{
ui.setupUi(this);
// Checkbox interlocks
addCheckEnabler(ui.titleCheck, ui.titleText);
addCheckEnabler(ui.moveCheck,
- (QList<QWidget *> ()
- << ui.daysLabel << ui.daysSpin
- << ui.hoursLabel<< ui.hoursSpin
- << ui.minsLabel << ui.minsSpin
- << ui.secsLabel << ui.secsSpin));
+ (QList<QWidget*> ()
+ << ui.daysLabel << ui.daysSpin
+ << ui.hoursLabel<< ui.hoursSpin
+ << ui.minsLabel << ui.minsSpin
+ << ui.secsLabel << ui.secsSpin));
addCheckEnabler(ui.startCheck, ui.startEdit);
addCheckEnabler(ui.stopCheck, ui.stopEdit);
addCheckEnabler(ui.GPSFixesCheck, ui.GPSFixesCombo);
- addCheckEnabler(ui.splitTimeCheck,
- (QList<QWidget *> ()
- <<ui.splitTimeSpin
- <<ui.splitTimeCombo));
- addCheckEnabler(ui.splitDistanceCheck,
- (QList<QWidget *> ()
- <<ui.splitDistSpin
- <<ui.splitDistCombo));
+ addCheckEnabler(ui.splitTimeCheck,
+ (QList<QWidget*> ()
+ <<ui.splitTimeSpin
+ <<ui.splitTimeCombo));
+ addCheckEnabler(ui.splitDistanceCheck,
+ (QList<QWidget*> ()
+ <<ui.splitDistSpin
+ <<ui.splitDistCombo));
- connect(ui.mergeCheck, SIGNAL(clicked()) , this, SLOT(mergeCheckX()));
+ connect(ui.mergeCheck, SIGNAL(clicked()), this, SLOT(mergeCheckX()));
connect(ui.packCheck, SIGNAL(clicked()), this, SLOT(packCheckX()));
connect(ui.startCheck, SIGNAL(clicked()), this, SLOT(otherCheckX()));
connect(ui.stopCheck, SIGNAL(clicked()), this, SLOT(otherCheckX()));
ui.splitTimeCombo->setEnabled(ui.splitTimeCheck->isChecked());
ui.splitDistSpin->setEnabled(ui.splitDistanceCheck->isChecked());
ui.splitDistCombo->setEnabled(ui.splitDistanceCheck->isChecked());
-
+
bool bb = (ui.mergeCheck->isChecked() || ui.packCheck->isChecked());
ui.splitDateCheck->setEnabled(bb);
ui.splitTimeCheck->setEnabled(bb);
//------------------------------------------------------------------------
void TrackWidget::mergeCheckX()
{
- if (ui.mergeCheck->isChecked())
+ if (ui.mergeCheck->isChecked()) {
ui.packCheck->setChecked(false);
+ }
otherCheckX();
}
//------------------------------------------------------------------------
void TrackWidget::packCheckX()
{
- if (ui.packCheck->isChecked())
+ if (ui.packCheck->isChecked()) {
ui.mergeCheck->setChecked(false);
+ }
otherCheckX();
}
//------------------------------------------------------------------------
//------------------------------------------------------------------------
-WayPtsWidget::WayPtsWidget(QWidget *parent, WayPtsFilterData &wfd): FilterWidget(parent) , wfd(wfd)
+WayPtsWidget::WayPtsWidget(QWidget* parent, WayPtsFilterData& wfd): FilterWidget(parent), wfd(wfd)
{
ui.setupUi(this);
addCheckEnabler(ui.duplicatesCheck,
- QList<QWidget*>() << ui.shortNamesCheck << ui.locationsCheck);
- addCheckEnabler(ui.positionCheck,
- QList<QWidget*>() << ui.positionText << ui.positionUnitCombo);
+ QList<QWidget*>() << ui.shortNamesCheck << ui.locationsCheck);
+ addCheckEnabler(ui.positionCheck,
+ QList<QWidget*>() << ui.positionText << ui.positionUnitCombo);
addCheckEnabler(ui.radiusCheck,
- QList<QWidget*>() << ui.latLabel << ui.latText << ui.longLabel <<
- ui.longText << ui.radiusUnitCombo << ui.radiusText);
+ QList<QWidget*>() << ui.latLabel << ui.latText << ui.longLabel <<
+ ui.longText << ui.radiusUnitCombo << ui.radiusText);
fopts << new BoolFilterOption(wfd.duplicates, ui.duplicatesCheck);
fopts << new BoolFilterOption(wfd.shortNames, ui.shortNamesCheck);
//------------------------------------------------------------------------
void WayPtsWidget::shortNamesCkX()
{
- if (!ui.shortNamesCheck->isChecked())
+ if (!ui.shortNamesCheck->isChecked()) {
ui.locationsCheck->setChecked(true);
+ }
}
//------------------------------------------------------------------------
void WayPtsWidget::locationsCkX()
{
- if (!ui.locationsCheck->isChecked())
+ if (!ui.locationsCheck->isChecked()) {
ui.shortNamesCheck->setChecked(true);
+ }
}
//------------------------------------------------------------------------
//------------------------------------------------------------------------
-RtTrkWidget::RtTrkWidget(QWidget *parent, RtTrkFilterData &rfd): FilterWidget(parent) , rfd(rfd)
+RtTrkWidget::RtTrkWidget(QWidget* parent, RtTrkFilterData& rfd): FilterWidget(parent), rfd(rfd)
{
ui.setupUi(this);
addCheckEnabler(ui.simplifyCheck,
- QList<QWidget*>() << ui.limitToLabel << ui.limitToSpin << ui.pointLabel);
+ QList<QWidget*>() << ui.limitToLabel << ui.limitToSpin << ui.pointLabel);
fopts << new BoolFilterOption(rfd.simplify_, ui.simplifyCheck);
fopts << new BoolFilterOption(rfd.reverse_, ui.reverseCheck);
//------------------------------------------------------------------------
//------------------------------------------------------------------------
-MiscFltWidget::MiscFltWidget(QWidget *parent, MiscFltFilterData &mfd): FilterWidget(parent) , mfd(mfd)
+MiscFltWidget::MiscFltWidget(QWidget* parent, MiscFltFilterData& mfd): FilterWidget(parent), mfd(mfd)
{
ui.setupUi(this);
ui.transformCombo->addItem(QString("%1 %2 %3").arg(tr("Tracks")).arg(QChar(8594)).arg(tr("Waypoints")));
ui.transformCombo->addItem(QString("%1 %2 %3").arg(tr("Tracks")).arg(QChar(8594)).arg(tr("Routes")));
ui.transformCombo->addItem(QString("%1 %2 %3").arg(tr("Waypoints")).arg(QChar(8594)).arg(tr("Tracks")));
addCheckEnabler(ui.transformCheck,
- QList<QWidget*>() << ui.transformCombo << ui.deleteCheck);
+ QList<QWidget*>() << ui.transformCombo << ui.deleteCheck);
fopts << new BoolFilterOption(mfd.transform_, ui.transformCheck);
fopts << new BoolFilterOption(mfd.swap_, ui.swapCheck);
class CheckEnabler: public QObject
{
Q_OBJECT
- public:
- CheckEnabler(QObject *parent, QAbstractButton *ck, QWidget *w): QObject(parent), checkBox(ck)
+public:
+ CheckEnabler(QObject* parent, QAbstractButton* ck, QWidget* w): QObject(parent), checkBox(ck)
{
widgetList << w;
connect(ck, SIGNAL(clicked()), this, SLOT(checkStatusChanged()));
checkStatusChanged();
fixWhatsThis();
}
- CheckEnabler(QObject *parent, QAbstractButton *ck, QList<QWidget *> &wl):
+ CheckEnabler(QObject* parent, QAbstractButton* ck, QList<QWidget*>& wl):
QObject(parent), checkBox(ck)
{
widgetList = wl;
widgetList[i]->setEnabled(b);
}
}
-
+
private:
- QAbstractButton *checkBox;
+ QAbstractButton* checkBox;
QList<QWidget*> widgetList;
void fixWhatsThis()
{
QString wts = checkBox->whatsThis();
if (wts.length() != 0) {
for (int i=0; i<widgetList.size(); i++) {
- QString s = widgetList[i]->whatsThis();
- if (s.length() == 0)
- widgetList[i]->setWhatsThis(wts);
+ QString s = widgetList[i]->whatsThis();
+ if (s.length() == 0) {
+ widgetList[i]->setWhatsThis(wts);
+ }
}
}
QString wtf = checkBox->toolTip();
if (wtf.length() != 0) {
for (int i=0; i<widgetList.size(); i++) {
- QString s = widgetList[i]->toolTip();
- if (s.length() == 0)
- widgetList[i]->setToolTip(wtf);
+ QString s = widgetList[i]->toolTip();
+ if (s.length() == 0) {
+ widgetList[i]->setToolTip(wtf);
+ }
}
}
}
//------------------------------------------------------------------------
class FilterOption
{
- public:
+public:
FilterOption() {};
virtual ~FilterOption() {};
virtual void setWidgetValue() = 0;
//------------------------------------------------------------------------
class BoolFilterOption: public FilterOption
{
- public:
- BoolFilterOption(bool &b, QAbstractButton *ck): FilterOption(), b(b), checkBox(ck)
+public:
+ BoolFilterOption(bool& b, QAbstractButton* ck): FilterOption(), b(b), checkBox(ck)
{
}
- void setWidgetValue() {checkBox->setChecked(b); }
- void getWidgetValue() {b = checkBox->isChecked(); }
-
- private:
- bool &b;
- QAbstractButton *checkBox;
+ void setWidgetValue()
+ {
+ checkBox->setChecked(b);
+ }
+ void getWidgetValue()
+ {
+ b = checkBox->isChecked();
+ }
+
+private:
+ bool& b;
+ QAbstractButton* checkBox;
};
//------------------------------------------------------------------------
class IntSpinFilterOption: public FilterOption
{
- public:
- IntSpinFilterOption(int &val, QSpinBox *sb, int bottom = -100, int top = 100): FilterOption(), val(val), spinBox(sb)
+public:
+ IntSpinFilterOption(int& val, QSpinBox* sb, int bottom = -100, int top = 100): FilterOption(), val(val), spinBox(sb)
{
sb->setRange(bottom, top);
}
- void setWidgetValue() {spinBox->setValue(val); }
- void getWidgetValue() {val = spinBox->value(); }
-
- private:
- int &val;
- QSpinBox *spinBox;
+ void setWidgetValue()
+ {
+ spinBox->setValue(val);
+ }
+ void getWidgetValue()
+ {
+ val = spinBox->value();
+ }
+
+private:
+ int& val;
+ QSpinBox* spinBox;
};
//------------------------------------------------------------------------
class StringFilterOption: public FilterOption
{
- public:
- StringFilterOption(QString &val, QLineEdit *le): FilterOption(), val(val), lineEdit(le)
+public:
+ StringFilterOption(QString& val, QLineEdit* le): FilterOption(), val(val), lineEdit(le)
+ {
+ }
+ void setWidgetValue()
+ {
+ lineEdit->setText(val);
+ }
+ void getWidgetValue()
{
+ val = lineEdit->text();
}
- void setWidgetValue() {lineEdit->setText(val); }
- void getWidgetValue() {val = lineEdit->text(); }
-
- private:
- QString &val;
- QLineEdit *lineEdit;
+
+private:
+ QString& val;
+ QLineEdit* lineEdit;
};
//------------------------------------------------------------------------
class DoubleFilterOption: public FilterOption
{
- public:
- DoubleFilterOption(double &val, QLineEdit *le,
- double minVal = -1.E308,
- double maxVal = 1.0E308,
- int decimals = -1,
- char format = 'g'
- ): FilterOption(), val(val), lineEdit(le), minVal(minVal),
- maxVal(maxVal), decimals(decimals), format(format)
+public:
+ DoubleFilterOption(double& val, QLineEdit* le,
+ double minVal = -1.E308,
+ double maxVal = 1.0E308,
+ int decimals = -1,
+ char format = 'g'
+ ): FilterOption(), val(val), lineEdit(le), minVal(minVal),
+ maxVal(maxVal), decimals(decimals), format(format)
{
le->setValidator(new QDoubleValidator(minVal, maxVal, decimals, le));
}
- void setWidgetValue() {
+ void setWidgetValue()
+ {
lineEdit->setText(QString("%1").arg(val, 0, format, decimals));
}
- void getWidgetValue() {
- val = lineEdit->text().toDouble();
+ void getWidgetValue()
+ {
+ val = lineEdit->text().toDouble();
val = qMin(val, maxVal);
val = qMax(val, minVal);
}
-
- private:
- double &val;
- QLineEdit *lineEdit;
+
+private:
+ double& val;
+ QLineEdit* lineEdit;
double minVal, maxVal;
int decimals;
char format;
//------------------------------------------------------------------------
class DateTimeFilterOption: public FilterOption
{
- public:
- DateTimeFilterOption(QDateTime &val, QDateTimeEdit *w): FilterOption(), val(val), w(w)
+public:
+ DateTimeFilterOption(QDateTime& val, QDateTimeEdit* w): FilterOption(), val(val), w(w)
+ {
+ }
+ void setWidgetValue()
+ {
+ w->setDateTime(val);
+ }
+ void getWidgetValue()
{
+ val = w->dateTime();
}
- void setWidgetValue() {w->setDateTime(val); }
- void getWidgetValue() {val = w->dateTime(); }
-
- private:
- QDateTime &val;
- QDateTimeEdit *w;
+
+private:
+ QDateTime& val;
+ QDateTimeEdit* w;
};
//------------------------------------------------------------------------
class ComboFilterOption: public FilterOption
{
- public:
- ComboFilterOption(int &val, QComboBox *w): FilterOption(), val(val), w(w)
+public:
+ ComboFilterOption(int& val, QComboBox* w): FilterOption(), val(val), w(w)
+ {
+ }
+ void setWidgetValue()
{
+ w->setCurrentIndex(val);
}
- void setWidgetValue() {w->setCurrentIndex(val); }
- void getWidgetValue() {val = w->currentIndex(); }
-
- private:
- int &val;
- QComboBox *w;
+ void getWidgetValue()
+ {
+ val = w->currentIndex();
+ }
+
+private:
+ int& val;
+ QComboBox* w;
};
class FilterWidget: public QWidget
{
public:
- FilterWidget(QWidget *parent) : QWidget(parent) {}
- ~FilterWidget() {
- for (int i=0; i<fopts.size(); i++)
+ FilterWidget(QWidget* parent) : QWidget(parent) {}
+ ~FilterWidget()
+ {
+ for (int i=0; i<fopts.size(); i++) {
delete fopts[i];
+ }
}
- void getWidgetValues() {
+ void getWidgetValues()
+ {
for (int i=0; i<fopts.size(); i++) {
fopts[i]->getWidgetValue();
}
}
- void setWidgetValues() {
- for (int i=0; i<fopts.size(); i++)
+ void setWidgetValues()
+ {
+ for (int i=0; i<fopts.size(); i++) {
fopts[i]->setWidgetValue();
+ }
}
- void addCheckEnabler(QAbstractButton *ck, QWidget *w) {
+ void addCheckEnabler(QAbstractButton* ck, QWidget* w)
+ {
enbls << new CheckEnabler(this, ck, w);
}
- void addCheckEnabler(QAbstractButton *ck, QList<QWidget *> &wl)
+ void addCheckEnabler(QAbstractButton* ck, QList<QWidget*>& wl)
{
enbls << new CheckEnabler(this, ck, wl);
}
- virtual void checkChecks(){
- for (int i=0; i<enbls.size(); i++)
+ virtual void checkChecks()
+ {
+ for (int i=0; i<enbls.size(); i++) {
enbls[i]->checkStatusChanged();
+ }
}
protected:
QList <FilterOption*> fopts;
- QList <CheckEnabler *> enbls;
+ QList <CheckEnabler*> enbls;
};
//------------------------------------------------------------------------
class TrackWidget: public FilterWidget
{
-Q_OBJECT
- public:
- TrackWidget(QWidget *parent, TrackFilterData &tf);
+ Q_OBJECT
+public:
+ TrackWidget(QWidget* parent, TrackFilterData& tf);
- virtual void checkChecks(){
+ virtual void checkChecks()
+ {
otherCheckX();
FilterWidget::checkChecks();
}
- private:
+private:
Ui_TrackWidget ui;
- TrackFilterData &tfd;
+ TrackFilterData& tfd;
- private slots:
+private slots:
void mergeCheckX();
void otherCheckX();
void splitDateX();
//------------------------------------------------------------------------
class WayPtsWidget: public FilterWidget
{
-Q_OBJECT
- public:
- WayPtsWidget(QWidget *parent, WayPtsFilterData &wf);
+ Q_OBJECT
+public:
+ WayPtsWidget(QWidget* parent, WayPtsFilterData& wf);
- private:
+private:
Ui_WayPtsWidget ui;
- WayPtsFilterData &wfd;
-
+ WayPtsFilterData& wfd;
+
private slots:
void locationsCkX();
void shortNamesCkX();
//------------------------------------------------------------------------
class RtTrkWidget: public FilterWidget
{
-Q_OBJECT
- public:
- RtTrkWidget(QWidget *parent, RtTrkFilterData &wf);
+ Q_OBJECT
+public:
+ RtTrkWidget(QWidget* parent, RtTrkFilterData& wf);
- private:
+private:
Ui_RtTrkWidget ui;
- RtTrkFilterData &rfd;
+ RtTrkFilterData& rfd;
};
//------------------------------------------------------------------------
class MiscFltWidget: public FilterWidget
{
-Q_OBJECT
- public:
- MiscFltWidget(QWidget *, MiscFltFilterData &);
+ Q_OBJECT
+public:
+ MiscFltWidget(QWidget*, MiscFltFilterData&);
- private:
+private:
Ui_MiscFltWidget ui;
- MiscFltFilterData &mfd;
+ MiscFltFilterData& mfd;
};
#endif
QString Format::htmlBase_ = QString();
-static void saveOptions(QSettings &settings, const QString &prefix, const QList<FormatOption> &options) {
+static void saveOptions(QSettings& settings, const QString& prefix, const QList<FormatOption>& options)
+{
for (int i=0; i<options.size(); i++) {
QString kp = prefix + "." + options[i].getName();
QString k1 = kp + ".selected";
}
}
-static void restoreOptions(QSettings &settings, const QString&prefix, QList<FormatOption> &options) {
+static void restoreOptions(QSettings& settings, const QString& prefix, QList<FormatOption>& options)
+{
for (int i=0; i<options.size(); i++) {
QString kp = prefix + "." + options[i].getName();
QString k1 = kp + ".selected";
}
}
-void Format::saveSettings(QSettings &settings)
+void Format::saveSettings(QSettings& settings)
{
saveOptions(settings, name_+".input", inputOptions_);
saveOptions(settings, name_+".output", outputOptions_);
settings.setValue(name_+".hidden", isHidden());
}
-void Format::restoreSettings(QSettings &settings)
+void Format::restoreSettings(QSettings& settings)
{
restoreOptions(settings, name_ + ".input", inputOptions_);
restoreOptions(settings, name_ + ".output", outputOptions_);
OPTinFile,
OPToutFile,
} optionType;
-
+
FormatOption(): name_(QString()), description_(QString()), type_(OPTbool),
- defaultValue_(QVariant()),
- minValue_(QVariant()), maxValue_(QVariant()),
- html_(QString()), value_(QVariant()), isSelected_(false)
+ defaultValue_(QVariant()),
+ minValue_(QVariant()), maxValue_(QVariant()),
+ html_(QString()), value_(QVariant()), isSelected_(false)
{
}
- FormatOption(const QString &name,
- const QString &description,
- optionType type,
- QVariant defaultValue = QVariant(),
- QVariant minValue = QVariant(),
- QVariant maxValue = QVariant(),
- QString html = QString()
- ): name_(name), description_(description), type_(type),
- defaultValue_(defaultValue), minValue_(minValue), maxValue_(maxValue), html_(html)
+ FormatOption(const QString& name,
+ const QString& description,
+ optionType type,
+ QVariant defaultValue = QVariant(),
+ QVariant minValue = QVariant(),
+ QVariant maxValue = QVariant(),
+ QString html = QString()
+ ): name_(name), description_(description), type_(type),
+ defaultValue_(defaultValue), minValue_(minValue), maxValue_(maxValue), html_(html)
{
value_ = QVariant();
- // Boolean values pay more atention to 'selected' than value. Make
+ // Boolean values pay more atention to 'selected' than value. Make
// them match here. For non-bools, just make them unchecked.
if (type_ == OPTbool && defaultValue.toBool() == true) {
isSelected_ = true;
}
}
- FormatOption(const FormatOption & c)
+ FormatOption(const FormatOption& c)
: name_(c.name_), description_(c.description_), type_(c.type_),
defaultValue_(c.defaultValue_), minValue_(c.minValue_), maxValue_(c.maxValue_), html_(c.html_),
value_(c.value_), isSelected_(c.isSelected_)
{
}
-
- QString getName() const {return name_; }
- QString getDescription() const {return description_; }
- optionType getType() const {return type_; }
- QVariant getValue() const { return value_; }
- bool getSelected() const {return isSelected_; }
- QVariant getMinValue() const {return minValue_; }
- QVariant getMaxValue() const {return maxValue_; }
- QVariant getDefaultValue() const {return defaultValue_; }
- void setValue(QVariant v) { value_ = v; };
- void setSelected(bool v) { isSelected_ = v; };
- QString getHtml() const { return html_; };
+ QString getName() const
+ {
+ return name_;
+ }
+ QString getDescription() const
+ {
+ return description_;
+ }
+ optionType getType() const
+ {
+ return type_;
+ }
+ QVariant getValue() const
+ {
+ return value_;
+ }
+ bool getSelected() const
+ {
+ return isSelected_;
+ }
+ QVariant getMinValue() const
+ {
+ return minValue_;
+ }
+ QVariant getMaxValue() const
+ {
+ return maxValue_;
+ }
+ QVariant getDefaultValue() const
+ {
+ return defaultValue_;
+ }
+
+ void setValue(QVariant v)
+ {
+ value_ = v;
+ };
+ void setSelected(bool v)
+ {
+ isSelected_ = v;
+ };
+ QString getHtml() const
+ {
+ return html_;
+ };
private:
QString name_;
//------------------------------------------------------------------------
-class Format
+class Format
{
- public:
+public:
Format():name_(QString()),
- description_(QString()),
- readWaypoints_(false),
- readTracks_(false),
- readRoutes_(false),
- writeWaypoints_(false),
- writeTracks_(false),
- writeRoutes_(false),
- fileFormat_(false),
- deviceFormat_(false),
- hidden_(false),
- extensions_(QStringList()),
- html_(QString()),
- readUseCount_(0),
- writeUseCount_(0)
+ description_(QString()),
+ readWaypoints_(false),
+ readTracks_(false),
+ readRoutes_(false),
+ writeWaypoints_(false),
+ writeTracks_(false),
+ writeRoutes_(false),
+ fileFormat_(false),
+ deviceFormat_(false),
+ hidden_(false),
+ extensions_(QStringList()),
+ html_(QString()),
+ readUseCount_(0),
+ writeUseCount_(0)
{
inputOptions_.clear();
outputOptions_.clear();
};
- Format(const QString &name,
- const QString &description,
- bool readWaypoints, bool readTracks, bool readRoutes,
- bool writeWaypoints, bool writeTracks, bool writeRoutes,
- bool fileFormat, bool deviceFormat,
- const QStringList &extensions,
- QList<FormatOption> &inputOptions,
- QList<FormatOption> &outputptions,
- const QString &html):
+ Format(const QString& name,
+ const QString& description,
+ bool readWaypoints, bool readTracks, bool readRoutes,
+ bool writeWaypoints, bool writeTracks, bool writeRoutes,
+ bool fileFormat, bool deviceFormat,
+ const QStringList& extensions,
+ QList<FormatOption>& inputOptions,
+ QList<FormatOption>& outputptions,
+ const QString& html):
name_(name), description_(description),
readWaypoints_(readWaypoints), readTracks_(readTracks), readRoutes_(readRoutes),
writeWaypoints_(writeWaypoints), writeTracks_(writeTracks), writeRoutes_(writeRoutes),
(void)html; // suppress 'unused' warning.
}
- Format(const Format &c):
+ Format(const Format& c):
name_(c.name_), description_(c.description_),
readWaypoints_(c.readWaypoints_), readTracks_(c.readTracks_), readRoutes_(c.readRoutes_),
writeWaypoints_(c.writeWaypoints_), writeTracks_(c.writeTracks_), writeRoutes_(c.writeRoutes_),
~Format() {};
- bool isReadWaypoints() const { return readWaypoints_; };
- bool isReadTracks() const { return readTracks_; };
- bool isReadRoutes() const { return readRoutes_; };
- bool isReadSomething() const {
- return isReadWaypoints() || isReadTracks () || isReadRoutes();
+ bool isReadWaypoints() const
+ {
+ return readWaypoints_;
+ };
+ bool isReadTracks() const
+ {
+ return readTracks_;
+ };
+ bool isReadRoutes() const
+ {
+ return readRoutes_;
+ };
+ bool isReadSomething() const
+ {
+ return isReadWaypoints() || isReadTracks() || isReadRoutes();
};
- bool isWriteWaypoints() const { return writeWaypoints_; };
- bool isWriteTracks() const { return writeTracks_; };
- bool isWriteRoutes() const { return writeRoutes_; };
- bool isWriteSomething() const {
- return isWriteWaypoints() || isWriteTracks () || isWriteRoutes();
+ bool isWriteWaypoints() const
+ {
+ return writeWaypoints_;
+ };
+ bool isWriteTracks() const
+ {
+ return writeTracks_;
+ };
+ bool isWriteRoutes() const
+ {
+ return writeRoutes_;
+ };
+ bool isWriteSomething() const
+ {
+ return isWriteWaypoints() || isWriteTracks() || isWriteRoutes();
};
- QString getName() const { return name_; };
- QString getDescription() const { return description_; };
- QString getHtml() const { return html_; };
- QStringList getExtensions() const { return extensions_; };
- const QList<FormatOption> &getInputOptions() const { return inputOptions_; };
- const QList<FormatOption> &getOutputOptions() const { return outputOptions_; };
+ QString getName() const
+ {
+ return name_;
+ };
+ QString getDescription() const
+ {
+ return description_;
+ };
+ QString getHtml() const
+ {
+ return html_;
+ };
+ QStringList getExtensions() const
+ {
+ return extensions_;
+ };
+ const QList<FormatOption>& getInputOptions() const
+ {
+ return inputOptions_;
+ };
+ const QList<FormatOption>& getOutputOptions() const
+ {
+ return outputOptions_;
+ };
+
+ QList<FormatOption>* getInputOptionsRef()
+ {
+ return &inputOptions_;
+ };
+ QList<FormatOption>* getOutputOptionsRef()
+ {
+ return &outputOptions_;
+ };
- QList<FormatOption> *getInputOptionsRef() { return &inputOptions_; };
- QList<FormatOption> *getOutputOptionsRef() { return &outputOptions_; };
+ bool isDeviceFormat() const
+ {
+ return deviceFormat_;
+ };
+ bool isFileFormat() const
+ {
+ return fileFormat_;
+ };
- bool isDeviceFormat() const { return deviceFormat_; };
- bool isFileFormat() const { return fileFormat_; };
+ bool isHidden() const
+ {
+ return hidden_;
+ };
+ void setHidden(bool state)
+ {
+ hidden_ = state;
+ };
- bool isHidden() const { return hidden_; };
- void setHidden(bool state) { hidden_ = state; };
-
- void saveSettings(QSettings &settings);
- void restoreSettings(QSettings &settings);
+ void saveSettings(QSettings& settings);
+ void restoreSettings(QSettings& settings);
void setToDefault();
- static QString getHtmlBase() { return htmlBase_; }
- static void setHtmlBase(const QString &s) { htmlBase_ = s; }
-
- void bumpReadUseCount(int v) { readUseCount_ += v; }
- void bumpWriteUseCount(int v) { writeUseCount_ += v; }
- int getReadUseCount() const { return readUseCount_; }
- int getWriteUseCount() const { return writeUseCount_; }
- void zeroUseCounts() {
+ static QString getHtmlBase()
+ {
+ return htmlBase_;
+ }
+ static void setHtmlBase(const QString& s)
+ {
+ htmlBase_ = s;
+ }
+
+ void bumpReadUseCount(int v)
+ {
+ readUseCount_ += v;
+ }
+ void bumpWriteUseCount(int v)
+ {
+ writeUseCount_ += v;
+ }
+ int getReadUseCount() const
+ {
+ return readUseCount_;
+ }
+ int getWriteUseCount() const
+ {
+ return writeUseCount_;
+ }
+ void zeroUseCounts()
+ {
readUseCount_ = 0;
writeUseCount_ = 0;
}
-
- private:
+
+private:
QString name_, description_;
bool readWaypoints_, readTracks_, readRoutes_;
bool writeWaypoints_, writeTracks_, writeRoutes_;
static QString htmlBase_;
int readUseCount_;
int writeUseCount_;
-
+
};
#endif
#include "appname.h"
//------------------------------------------------------------------------
-static QString xlt(const QString &f) {
+static QString xlt(const QString& f)
+{
return QCoreApplication::translate("", f.toStdString().c_str());
}
bool FormatLoad::skipToValidLine()
{
QRegExp regex("^(file|serial)");
- while (currentLine_ <lines_.size() && regex.indexIn(lines_[currentLine_]) != 0)
+ while (currentLine_ <lines_.size() && regex.indexIn(lines_[currentLine_]) != 0) {
currentLine_++;
+ }
return (currentLine_<lines_.size());
}
//------------------------------------------------------------------------
-bool FormatLoad::processFormat(Format &format)
+bool FormatLoad::processFormat(Format& format)
{
QStringList hfields = lines_[currentLine_++].split("\t");
if (hfields.size() < 5) {
QString optionMax = ofields[7];
QString optionHtml = ofields[8];
FormatOption::optionType type = FormatOption::OPTbool;
- if (optionType == "boolean")
+ if (optionType == "boolean") {
type = FormatOption::OPTbool;
- else if (optionType == "string")
+ } else if (optionType == "string") {
type = FormatOption::OPTstring;
- else if (optionType == "integer") {
+ } else if (optionType == "integer") {
type = (optionMax != "" && optionMin != "") ? FormatOption::OPTboundedInt : FormatOption::OPTint;
- if (optionMax == "")
- optionMax = "2147483647";
- if (optionMin == "")
- optionMin = "-2147483647";
- }
- else if (optionType == "float") {
+ if (optionMax == "") {
+ optionMax = "2147483647";
+ }
+ if (optionMin == "") {
+ optionMin = "-2147483647";
+ }
+ } else if (optionType == "float") {
type = FormatOption::OPTfloat;
- if (optionMax == "")
- optionMax = "1.0E308";
- if (optionMin == "")
- optionMin = "-1.0E308";
- }
- else if (optionType == "file") {
+ if (optionMax == "") {
+ optionMax = "1.0E308";
+ }
+ if (optionMin == "") {
+ optionMin = "-1.0E308";
+ }
+ } else if (optionType == "file") {
type = FormatOption::OPTinFile;
- }
- else if (optionType == "outfile") {
+ } else if (optionType == "outfile") {
type = FormatOption::OPToutFile;
- }
- else {
+ } else {
type = FormatOption::OPTstring;
}
optionList << FormatOption(name, xlt(description),
- type, QVariant(optionDef), QVariant(optionMin),
- QVariant(optionMax), optionHtml);
+ type, QVariant(optionDef), QVariant(optionMin),
+ QVariant(optionMax), optionHtml);
currentLine_++;
}
QList <FormatOption> optionList2 = optionList;
format = Format(hfields[2], xlt(hfields[4]),
- hfields[1][0] == QChar('r'), hfields[1][2] == QChar('r'), hfields[1][4] == QChar('r'),
- hfields[1][1] == QChar('w'), hfields[1][3] == QChar('w'), hfields[1][5] == QChar('w'),
- hfields[0] == "file",
- hfields[0] == "serial",
- hfields[3].split('/'),
- optionList,
- optionList2, htmlPage);
+ hfields[1][0] == QChar('r'), hfields[1][2] == QChar('r'), hfields[1][4] == QChar('r'),
+ hfields[1][1] == QChar('w'), hfields[1][3] == QChar('w'), hfields[1][5] == QChar('w'),
+ hfields[0] == "file",
+ hfields[0] == "serial",
+ hfields[3].split('/'),
+ optionList,
+ optionList2, htmlPage);
if (htmlPage.length() > 0 && Format::getHtmlBase().length() == 0) {
QString base = htmlPage;
base.replace(QRegExp("/[^/]+$"), "/");
}
//------------------------------------------------------------------------
-bool FormatLoad::getFormats(QList<Format> &formatList)
+bool FormatLoad::getFormats(QList<Format>& formatList)
{
formatList.clear();
QProcess babel;
babel.start("gpsbabel", QStringList() << "-^3");
- if (!babel.waitForStarted())
+ if (!babel.waitForStarted()) {
return false;
+ }
babel.closeWriteChannel();
- if (!babel.waitForFinished())
+ if (!babel.waitForFinished()) {
return false;
- if (babel.exitCode() != 0)
+ }
+ if (babel.exitCode() != 0) {
return false;
+ }
QTextStream tstream(babel.readAll());
QList<int>lineList;
int k=0;
- while(!tstream.atEnd()) {
+ while (!tstream.atEnd()) {
QString l = tstream.readLine();
k++;
if (!QRegExp("^[\\s]*$").exactMatch(l)) {
}
currentLine_ = 0;
- for (bool dataPresent = skipToValidLine(); dataPresent; dataPresent=skipToValidLine()) {
+ for (bool dataPresent = skipToValidLine(); dataPresent; dataPresent=skipToValidLine()) {
Format format;
if (!processFormat(format)) {
QMessageBox::information
- (0, appName,
- QObject::tr("Error processing formats from running process \"gpsbabel -^3\" at line %1").arg(lineList[currentLine_]));
- }
- else {
+ (0, appName,
+ QObject::tr("Error processing formats from running process \"gpsbabel -^3\" at line %1").arg(lineList[currentLine_]));
+ } else {
formatList << format;
}
}
#include "format.h"
-class FormatLoad {
- public:
+class FormatLoad
+{
+public:
FormatLoad() : currentLine_(0) {};
~FormatLoad() {};
-
- bool getFormats(QList<Format> &formatList);
- private:
+
+ bool getFormats(QList<Format>& formatList);
+private:
QStringList lines_;
int currentLine_;
bool skipToValidLine();
- bool processFormat(Format &format);
+ bool processFormat(Format& format);
};
#endif
//------------------------------------------------------------------------
class StandardItem: public QStandardItem
{
- public:
- StandardItem(const QString &text): QStandardItem(text)
- {
- this->setEditable(false);
- }
+public:
+ StandardItem(const QString& text): QStandardItem(text)
+ {
+ this->setEditable(false);
+ }
};
//------------------------------------------------------------------------
class TreeAction: public QAction
{
public:
- TreeAction(const QString &text,
- QObject *obj, const char *member, QObject *parent): QAction(text, parent)
+ TreeAction(const QString& text,
+ QObject* obj, const char* member, QObject* parent): QAction(text, parent)
{
connect(this, SIGNAL(triggered()), obj, member);
}
fpsPrecision = 3;
}
return QString(tr("Length: %1 %2\n %3 %4")
- .arg(metricLength, 0, 'f', metricPrecision)
- .arg(metricUnit)
- .arg(fpsLength, 0, 'f', fpsPrecision)
- .arg(fpsUnit));
+ .arg(metricLength, 0, 'f', metricPrecision)
+ .arg(metricUnit)
+ .arg(fpsLength, 0, 'f', fpsPrecision)
+ .arg(fpsUnit));
}
//------------------------------------------------------------------------
-void GMapDialog::appendWaypointInfo(QStandardItem *it, const GpxWaypoint &wpt)
+void GMapDialog::appendWaypointInfo(QStandardItem* it, const GpxWaypoint& wpt)
{
it->appendRow(new StandardItem(tr("Lat: %1").arg(wpt.getLocation().lat(), 0, 'f', 7)));
it->appendRow(new StandardItem(tr("Lng: %1").arg(wpt.getLocation().lng(), 0, 'f', 7)));
- if (wpt.getDescription() != QString())
+ if (wpt.getDescription() != QString()) {
it->appendRow(new StandardItem(tr("Desc: %1").arg(wpt.getDescription())));
- if (wpt.getComment() != QString() && wpt.getComment() != wpt.getDescription())
+ }
+ if (wpt.getComment() != QString() && wpt.getComment() != wpt.getDescription()) {
it->appendRow(new StandardItem(tr("Cmt: %1").arg(wpt.getComment())));
- if (wpt.getElevation() > -50000)
+ }
+ if (wpt.getElevation() > -50000) {
it->appendRow(new StandardItem(tr("Ele: %1").arg(wpt.getElevation())));
+ }
}
//------------------------------------------------------------------------
-void GMapDialog::appendTrackInfo(QStandardItem *it, const GpxTrack &trk)
+void GMapDialog::appendTrackInfo(QStandardItem* it, const GpxTrack& trk)
{
QDateTime startTime, stopTime;
bool first = true;
int count = 0;
- foreach (const GpxTrackSegment &seg, trk.getTrackSegments()) {
- foreach (const GpxTrackPoint &pt, seg.getTrackPoints()) {
+ foreach (const GpxTrackSegment& seg, trk.getTrackSegments()) {
+ foreach (const GpxTrackPoint& pt, seg.getTrackPoints()) {
count++;
QDateTime t = pt.getDateTime();
- if (!t.isValid())
- continue;
- if (first) {
- startTime = t;
- stopTime = t;
- first = false;
+ if (!t.isValid()) {
+ continue;
}
- else {
- if (t < startTime)
- startTime = t;
- if (t > stopTime)
- stopTime = t;
+ if (first) {
+ startTime = t;
+ stopTime = t;
+ first = false;
+ } else {
+ if (t < startTime) {
+ startTime = t;
+ }
+ if (t > stopTime) {
+ stopTime = t;
+ }
}
}
}
if (startTime.isValid()) {
it->appendRow(new StandardItem(tr("Start: %1")
- .arg(startTime.toString("yyyy-MMM-dd HH:mm:ss"))));
+ .arg(startTime.toString("yyyy-MMM-dd HH:mm:ss"))));
it->appendRow(new StandardItem(tr("Stop: %1")
- .arg(stopTime.toString("yyyy-MMM-dd HH:mm:ss"))));
+ .arg(stopTime.toString("yyyy-MMM-dd HH:mm:ss"))));
}
it->appendRow(new StandardItem(tr("Points: %1").arg(count)));
}
//------------------------------------------------------------------------
-void GMapDialog::appendRouteInfo(QStandardItem *it, const GpxRoute &rte)
+void GMapDialog::appendRouteInfo(QStandardItem* it, const GpxRoute& rte)
{
it->appendRow(new StandardItem(formatLength(rte.length())));
}
//------------------------------------------------------------------------
-GMapDialog::GMapDialog(QWidget *parent, const QString &gpxFileName, QPlainTextEdit *te): QDialog(parent)
+GMapDialog::GMapDialog(QWidget* parent, const QString& gpxFileName, QPlainTextEdit* te): QDialog(parent)
{
ui_.setupUi(this);
this->setWindowTitle(QString(appName) + " " + QString("Google Maps"));
gpx_.read(gpxFileName);
mapWidget_ = new Map(this, gpx_, te);
- QHBoxLayout *lay = new QHBoxLayout(ui_.frame);
+ QHBoxLayout* lay = new QHBoxLayout(ui_.frame);
lay->setContentsMargins(0, 0, 0, 0);
lay->addWidget(mapWidget_);
wptItem_->setCheckState(Qt::Checked);
model_->appendRow(wptItem_);
for (int i=0; i<gpx_.getWaypoints().size(); i++) {
- GpxWaypoint &wpt = gpx_.getWaypoints()[i];
- QStandardItem *it = new StandardItem(wpt.getName());
+ GpxWaypoint& wpt = gpx_.getWaypoints()[i];
+ QStandardItem* it = new StandardItem(wpt.getName());
wptItem_->appendRow(it);
it->setCheckable(true);
it->setCheckState(Qt::Checked);
- it->setData(qVariantFromValue((void *)&wpt));
+ it->setData(qVariantFromValue((void*)&wpt));
appendWaypointInfo(it, wpt);
wptList_ << it;
}
trkItem_->setCheckState(Qt::Checked);
model_->appendRow(trkItem_);
for (int i=0; i<gpx_.getTracks().size(); i++) {
- GpxTrack &trk = gpx_.getTracks()[i];
- QStandardItem *it = new StandardItem(trk.getName());
+ GpxTrack& trk = gpx_.getTracks()[i];
+ QStandardItem* it = new StandardItem(trk.getName());
trkItem_->appendRow(it);
it->setCheckable(true);
it->setCheckState(Qt::Checked);
- it->setData(qVariantFromValue((void *)&trk));
+ it->setData(qVariantFromValue((void*)&trk));
appendTrackInfo(it, trk);
trkList_ << it;
}
rteItem_->setCheckState(Qt::Checked);
model_->appendRow(rteItem_);
for (int i=0; i<gpx_.getRoutes().size(); i++) {
- GpxRoute &rte = gpx_.getRoutes()[i];
- QStandardItem *it = new StandardItem(rte.getName());
+ GpxRoute& rte = gpx_.getRoutes()[i];
+ QStandardItem* it = new StandardItem(rte.getName());
rteItem_->appendRow(it);
it->setCheckable(true);
it->setCheckState(Qt::Checked);
- it->setData(qVariantFromValue((void *)&rte));
+ it->setData(qVariantFromValue((void*)&rte));
appendRouteInfo(it, rte);
rteList_ << it;
}
ui_.treeView->header()->hide();
ui_.treeView->setModel(model_);
ui_.treeView->setExpandsOnDoubleClick(false);
- connect(model_, SIGNAL(itemChanged(QStandardItem *)),
- this, SLOT(itemChangedX(QStandardItem *)));
+ connect(model_, SIGNAL(itemChanged(QStandardItem*)),
+ this, SLOT(itemChangedX(QStandardItem*)));
connect(mapWidget_, SIGNAL(waypointClicked(int)), this, SLOT(waypointClickedX(int)));
connect(mapWidget_, SIGNAL(routeClicked(int)), this, SLOT(routeClickedX(int)));
connect(mapWidget_, SIGNAL(trackClicked(int)), this, SLOT(trackClickedX(int)));
- connect(ui_.treeView, SIGNAL(doubleClicked(const QModelIndex &)),
- this, SLOT(treeDoubleClicked(const QModelIndex&)));
- connect(ui_.treeView->selectionModel(), SIGNAL(selectionChanged (const QItemSelection &, const QItemSelection &)),
- this, SLOT(selectionChangedX(const QItemSelection &, const QItemSelection &)));
-
+ connect(ui_.treeView, SIGNAL(doubleClicked(const QModelIndex&)),
+ this, SLOT(treeDoubleClicked(const QModelIndex&)));
+ connect(ui_.treeView->selectionModel(), SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)),
+ this, SLOT(selectionChangedX(const QItemSelection&, const QItemSelection&)));
+
ui_.treeView->setContextMenuPolicy(Qt::CustomContextMenu);
- connect(ui_.treeView, SIGNAL(customContextMenuRequested(const QPoint &)),
- this, SLOT(showContextMenu(const QPoint &)));
+ connect(ui_.treeView, SIGNAL(customContextMenuRequested(const QPoint&)),
+ this, SLOT(showContextMenu(const QPoint&)));
connect(ui_.copyButton, SIGNAL(clicked()), this, SLOT(copyButtonClickedX()));
}
//-------------------------------------------------------------------------
-void GMapDialog::itemChangedX(QStandardItem *it)
+void GMapDialog::itemChangedX(QStandardItem* it)
{
bool show = (it->checkState() == Qt::Checked);
if (it == trkItem_) {
- if (show)
+ if (show) {
mapWidget_->showTracks(gpx_.getTracks());
- else
+ } else {
mapWidget_->hideAllTracks();
+ }
}
else if (it == wptItem_) {
- if (show)
+ if (show) {
mapWidget_->showWaypoints(gpx_.getWaypoints());
- else
+ } else {
mapWidget_->hideAllWaypoints();
+ }
}
else if (it == rteItem_) {
- if (show)
+ if (show) {
mapWidget_->showRoutes(gpx_.getRoutes());
- else
+ } else {
mapWidget_->hideAllRoutes();
+ }
}
else {
// Individual items, find the right one.
- GpxItem *git = static_cast<GpxItem *>(it->data().value<void *>());
+ GpxItem* git = static_cast<GpxItem*>(it->data().value<void*>());
if (git != 0) {
git->setVisible(show);
for (int i=0; i<gpx_.getWaypoints().size(); i++) {
- if (&gpx_.getWaypoints()[i] == git) {
- mapWidget_->setWaypointVisibility(i, show);
- }
+ if (&gpx_.getWaypoints()[i] == git) {
+ mapWidget_->setWaypointVisibility(i, show);
+ }
}
for (int i=0; i<gpx_.getTracks().size(); i++) {
- if (&gpx_.getTracks()[i] == git) {
- mapWidget_->setTrackVisibility(i, show);
- }
+ if (&gpx_.getTracks()[i] == git) {
+ mapWidget_->setTrackVisibility(i, show);
+ }
}
for (int i=0; i<gpx_.getRoutes().size(); i++) {
- if (&gpx_.getRoutes()[i] == git) {
- mapWidget_->setRouteVisibility(i, show);
- }
+ if (&gpx_.getRoutes()[i] == git) {
+ mapWidget_->setRouteVisibility(i, show);
+ }
}
}
}
}
//-------------------------------------------------------------------------
-int GMapDialog::waypointIndex(QStandardItem *it)
+int GMapDialog::waypointIndex(QStandardItem* it)
{
- for (int j=0; j<wptList_.size(); j++){
- if (it == wptList_[j])
+ for (int j=0; j<wptList_.size(); j++) {
+ if (it == wptList_[j]) {
return j;
+ }
}
return -1;
}
//-------------------------------------------------------------------------
-int GMapDialog::trackIndex(QStandardItem *it)
+int GMapDialog::trackIndex(QStandardItem* it)
{
- for (int j=0; j<trkList_.size(); j++){
- if (it == trkList_[j])
+ for (int j=0; j<trkList_.size(); j++) {
+ if (it == trkList_[j]) {
return j;
+ }
}
return -1;
}
//-------------------------------------------------------------------------
-int GMapDialog::routeIndex(QStandardItem *it)
+int GMapDialog::routeIndex(QStandardItem* it)
{
- for (int j=0; j<rteList_.size(); j++){
- if (it == rteList_[j])
+ for (int j=0; j<rteList_.size(); j++) {
+ if (it == rteList_[j]) {
return j;
+ }
}
return -1;
}
//-------------------------------------------------------------------------
-void GMapDialog::treeDoubleClicked(const QModelIndex &idx)
+void GMapDialog::treeDoubleClicked(const QModelIndex& idx)
{
- QStandardItem *it = model_->itemFromIndex(idx);
+ QStandardItem* it = model_->itemFromIndex(idx);
int i = waypointIndex(it);
if (i >= 0) {
it->setCheckState(Qt::Checked);
void GMapDialog::waypointClickedX(int i)
{
if (i>=0 && i < wptList_.size()) {
- QStandardItem *it = wptList_[i];
+ QStandardItem* it = wptList_[i];
QModelIndex idx = model_->indexFromItem(it);
ui_.treeView->scrollTo(idx, QAbstractItemView::PositionAtCenter);
ui_.treeView->selectionModel()->select(idx, QItemSelectionModel::ClearAndSelect);
void GMapDialog::trackClickedX(int i)
{
if (i>=0 && i <trkList_.size()) {
- QStandardItem *it = trkList_[i];
+ QStandardItem* it = trkList_[i];
QModelIndex idx = model_->indexFromItem(it);
ui_.treeView->scrollTo(idx, QAbstractItemView::PositionAtCenter);
ui_.treeView->selectionModel()->select(idx, QItemSelectionModel::ClearAndSelect);
void GMapDialog::routeClickedX(int i)
{
if (i>=0 && i <rteList_.size()) {
- QStandardItem *it = rteList_[i];
+ QStandardItem* it = rteList_[i];
QModelIndex idx = model_->indexFromItem(it);
ui_.treeView->scrollTo(idx, QAbstractItemView::PositionAtCenter);
ui_.treeView->selectionModel()->select(idx, QItemSelectionModel::ClearAndSelect);
}
//-------------------------------------------------------------------------
-void GMapDialog::selectionChangedX (const QItemSelection &sel, const QItemSelection &desel)
+void GMapDialog::selectionChangedX(const QItemSelection& sel, const QItemSelection& desel)
{
int k=0;
- foreach (QStandardItem*w, wptList_) {
+ foreach (QStandardItem* w, wptList_) {
QModelIndex idx = model_->indexFromItem(w);
- if (desel.contains(idx))
+ if (desel.contains(idx)) {
mapWidget_->setWaypointColorBlue(k);
- if (sel.contains(idx))
+ }
+ if (sel.contains(idx)) {
mapWidget_->setWaypointColorRed(k);
+ }
k++;
}
}
//------------------------------------------------------------------------
-void GMapDialog::expandCollapseAll(const QList<QStandardItem *> &li,
- QStandardItem *top, bool exp)
+void GMapDialog::expandCollapseAll(const QList<QStandardItem*>& li,
+ QStandardItem* top, bool exp)
{
ui_.treeView->setExpanded(model_->indexFromItem(top), exp);
- foreach (QStandardItem*it, li) {
+ foreach (QStandardItem* it, li) {
QModelIndex idx = model_->indexFromItem(it);
ui_.treeView->setExpanded(idx, exp);
}
}
//------------------------------------------------------------------------
-void GMapDialog::checkUncheckAll(const QList<QStandardItem *> &li,
- QStandardItem *top, bool ck)
+void GMapDialog::checkUncheckAll(const QList<QStandardItem*>& li,
+ QStandardItem* top, bool ck)
{
top->setCheckState(ck ? Qt::Checked: Qt::Unchecked);
- foreach (QStandardItem*it, li) {
+ foreach (QStandardItem* it, li) {
it->setCheckState(ck ? Qt::Checked: Qt::Unchecked);
}
}
//------------------------------------------------------------------------
void GMapDialog::showAllWaypoints()
{
- foreach (GpxWaypoint wpt, gpx_.getWaypoints())
+ foreach (GpxWaypoint wpt, gpx_.getWaypoints()) {
wpt.setVisible(true);
+ }
checkUncheckAll(wptList_, wptItem_, true);
mapWidget_->showWaypoints(gpx_.getWaypoints());
}
//------------------------------------------------------------------------
void GMapDialog::showAllTracks()
{
- foreach (GpxTrack trk, gpx_.getTracks())
+ foreach (GpxTrack trk, gpx_.getTracks()) {
trk.setVisible(true);
+ }
checkUncheckAll(trkList_, trkItem_, true);
mapWidget_->showTracks(gpx_.getTracks());
}
//------------------------------------------------------------------------
void GMapDialog::showAllRoutes()
{
- foreach (GpxRoute rte, gpx_.getRoutes())
+ foreach (GpxRoute rte, gpx_.getRoutes()) {
rte.setVisible(true);
+ }
checkUncheckAll(rteList_, rteItem_, true);
mapWidget_->showRoutes(gpx_.getRoutes());
}
//------------------------------------------------------------------------
void GMapDialog::hideAllWaypoints()
{
- foreach (GpxWaypoint wpt, gpx_.getWaypoints())
+ foreach (GpxWaypoint wpt, gpx_.getWaypoints()) {
wpt.setVisible(false);
+ }
checkUncheckAll(wptList_, wptItem_, false);
mapWidget_->showWaypoints(gpx_.getWaypoints());
}
//------------------------------------------------------------------------
void GMapDialog::hideAllTracks()
{
- foreach (GpxTrack trk, gpx_.getTracks())
+ foreach (GpxTrack trk, gpx_.getTracks()) {
trk.setVisible(false);
+ }
checkUncheckAll(trkList_, trkItem_, false);
mapWidget_->showTracks(gpx_.getTracks());
//------------------------------------------------------------------------
void GMapDialog::hideAllRoutes()
{
- foreach (GpxRoute rte, gpx_.getRoutes())
+ foreach (GpxRoute rte, gpx_.getRoutes()) {
rte.setVisible(false);
+ }
checkUncheckAll(rteList_, rteItem_, false);
mapWidget_->showRoutes(gpx_.getRoutes());
//------------------------------------------------------------------------
void GMapDialog::showOnlyThisWaypoint()
{
- QList <GpxWaypoint> &tlist = gpx_.getWaypoints();
+ QList <GpxWaypoint>& tlist = gpx_.getWaypoints();
for (int i=0; i<tlist.size(); i++) {
tlist[i].setVisible(i == menuIndex_? true: false);
trkList_[i]->setCheckState(i==menuIndex_? Qt::Checked: Qt::Unchecked);
//------------------------------------------------------------------------
void GMapDialog::showOnlyThisTrack()
{
- QList <GpxTrack> &tlist = gpx_.getTracks();
+ QList <GpxTrack>& tlist = gpx_.getTracks();
for (int i=0; i<tlist.size(); i++) {
tlist[i].setVisible(i == menuIndex_? true: false);
trkList_[i]->setCheckState(i==menuIndex_? Qt::Checked: Qt::Unchecked);
//------------------------------------------------------------------------
void GMapDialog::showOnlyThisRoute()
{
- QList <GpxRoute> &rlist = gpx_.getRoutes();
+ QList <GpxRoute>& rlist = gpx_.getRoutes();
for (int i=0; i<rlist.size(); i++) {
rlist[i].setVisible(i == menuIndex_? true: false);
rteList_[i]->setCheckState(i==menuIndex_? Qt::Checked: Qt::Unchecked);
}
//------------------------------------------------------------------------
-void GMapDialog::showContextMenu(const QPoint &pt)
+void GMapDialog::showContextMenu(const QPoint& pt)
{
QModelIndex idx = ui_.treeView->indexAt(pt);
- QStandardItem *it = model_->itemFromIndex(idx);
+ QStandardItem* it = model_->itemFromIndex(idx);
int j;
if (model_->indexFromItem(wptItem_) == idx) {
QMenu menu(this);
menu.addAction(new TreeAction(tr("Expand All"), this, SLOT(expandAllWaypoints()),&menu));
menu.addAction(new TreeAction(tr("Collapse All"), this, SLOT(collapseAllWaypoints()),&menu));
menu.exec(ui_.treeView->mapToGlobal(pt));
- }
- else if (model_->indexFromItem(rteItem_) == idx) {
+ } else if (model_->indexFromItem(rteItem_) == idx) {
QMenu menu(this);
menu.addAction(new TreeAction(tr("Show All Routes"), this, SLOT(showAllRoutes()), &menu));
menu.addAction(new TreeAction(tr("Hide All Routes"), this, SLOT(hideAllRoutes()),&menu));
menu.addAction(new TreeAction(tr("Expand All"), this, SLOT(expandAllRoutes()),&menu));
menu.addAction(new TreeAction(tr("Collapse All"), this, SLOT(collapseAllRoutes()),&menu));
menu.exec(ui_.treeView->mapToGlobal(pt));
- }
- else if (model_->indexFromItem(trkItem_) == idx) {
+ } else if (model_->indexFromItem(trkItem_) == idx) {
QMenu menu(this);
menu.addAction(new TreeAction(tr("Show All Tracks"), this, SLOT(showAllTracks()), &menu));
menu.addAction(new TreeAction(tr("Hide All Tracks"), this, SLOT(hideAllTracks()),&menu));
menu.addAction(new TreeAction(tr("Expand All"), this, SLOT(expandAllTracks()),&menu));
menu.addAction(new TreeAction(tr("Collapse All"), this, SLOT(collapseAllTracks()),&menu));
menu.exec(ui_.treeView->mapToGlobal(pt));
- }
- else if ((j = waypointIndex(it)) >=0) {
+ } else if ((j = waypointIndex(it)) >=0) {
QMenu menu(this);
menu.addAction(new TreeAction(tr("Show Only This Waypoint"), this, SLOT(showOnlyThisWaypoint()), &menu));
menuIndex_ = j;
menu.exec(ui_.treeView->mapToGlobal(pt));
- }
- else if ((j = trackIndex(it)) >=0) {
+ } else if ((j = trackIndex(it)) >=0) {
QMenu menu(this);
menu.addAction(new TreeAction(tr("Show Only This Track"), this, SLOT(showOnlyThisTrack()), &menu));
menuIndex_ = j;
menu.exec(ui_.treeView->mapToGlobal(pt));
- }
- else if ((j = routeIndex(it)) >=0) {
+ } else if ((j = routeIndex(it)) >=0) {
QMenu menu(this);
menu.addAction(new TreeAction(tr("Show Only This Route"), this, SLOT(showOnlyThisRoute()), &menu));
menuIndex_ = j;
menu.exec(ui_.treeView->mapToGlobal(pt));
- }
- else {
+ } else {
}
}
//------------------------------------------------------------------------
-void GMapDialog::copyButtonClickedX() {
-
+void GMapDialog::copyButtonClickedX()
+{
+
}
class GMapDialog: public QDialog
{
-Q_OBJECT
- public:
- GMapDialog(QWidget *parent, const QString &gpxFileName, QPlainTextEdit *te);
+ Q_OBJECT
+public:
+ GMapDialog(QWidget* parent, const QString& gpxFileName, QPlainTextEdit* te);
- private:
+private:
Ui_GMapDlg ui_;
- Map *mapWidget_;
- QStandardItemModel *model_;
- QStandardItem *wptItem_, *trkItem_, *rteItem_;
- QList<QStandardItem *> wptList_, trkList_, rteList_;
+ Map* mapWidget_;
+ QStandardItemModel* model_;
+ QStandardItem* wptItem_, *trkItem_, *rteItem_;
+ QList<QStandardItem*> wptList_, trkList_, rteList_;
Gpx gpx_;
int menuIndex_;
- void appendWaypointInfo(QStandardItem *it, const GpxWaypoint &wpt);
- void appendTrackInfo(QStandardItem *it, const GpxTrack &trk);
- void appendRouteInfo(QStandardItem *it, const GpxRoute &rte);
+ void appendWaypointInfo(QStandardItem* it, const GpxWaypoint& wpt);
+ void appendTrackInfo(QStandardItem* it, const GpxTrack& trk);
+ void appendRouteInfo(QStandardItem* it, const GpxRoute& rte);
- int waypointIndex(QStandardItem *it);
- int trackIndex(QStandardItem *it);
- int routeIndex(QStandardItem *it);
+ int waypointIndex(QStandardItem* it);
+ int trackIndex(QStandardItem* it);
+ int routeIndex(QStandardItem* it);
QString formatLength(double l);
//
private slots:
- void itemChangedX(QStandardItem *);
+ void itemChangedX(QStandardItem*);
void waypointClickedX(int i);
void trackClickedX(int i);
void routeClickedX(int i);
- void treeDoubleClicked(const QModelIndex &idx);
- void selectionChangedX (const QItemSelection &, const QItemSelection &);
+ void treeDoubleClicked(const QModelIndex& idx);
+ void selectionChangedX(const QItemSelection&, const QItemSelection&);
void copyButtonClickedX();
- void showContextMenu(const QPoint &);
+ void showContextMenu(const QPoint&);
- void expandCollapseAll(const QList<QStandardItem *> &li,
- QStandardItem *it, bool exp);
- void checkUncheckAll(const QList<QStandardItem *> &li,
- QStandardItem *it, bool exp);
+ void expandCollapseAll(const QList<QStandardItem*>& li,
+ QStandardItem* it, bool exp);
+ void checkUncheckAll(const QList<QStandardItem*>& li,
+ QStandardItem* it, bool exp);
void expandAllWaypoints();
void expandAllTracks();
void expandAllRoutes();
return utc;
}
-static bool trackIsEmpty(const GpxTrack &trk){
+static bool trackIsEmpty(const GpxTrack& trk)
+{
int count = 0;
for (int i=0; i< trk.getTrackSegments().size(); i++) {
for (int j=0; j<trk.getTrackSegments()[i].getTrackPoints().size(); j++) {
}
typedef enum {e_noop, e_wpt, e_trk,
- e_trkpt, e_trkseg, e_rte, e_rtept} elementState;
+ e_trkpt, e_trkseg, e_rte, e_rtept
+ } elementState;
QString textChars;
GpxWaypoint currentWpt;
QList <GpxWaypoint> wptList;
elementState state;
QList <elementState> stateStack;
- virtual bool startElement (const QString & ,
- const QString & localName, const QString &,
- const QXmlAttributes & atts )
+ virtual bool startElement(const QString&,
+ const QString& localName, const QString&,
+ const QXmlAttributes& atts)
{
if (localName == "wpt") {
currentWpt = GpxWaypoint();
else if (state == e_wpt ||
- state == e_trkpt || state == e_trkseg || state == e_trk ||
- state == e_rte || state == e_rtept) {
- }
- else {
+ state == e_trkpt || state == e_trkseg || state == e_trk ||
+ state == e_rte || state == e_rtept) {
+ } else {
//fprintf(stderr, "localName: %s name: %s\n",
//localName.toStdString().c_str(), qName.toStdString().c_str());
}
return true;
};
- virtual bool endElement (const QString & ,
- const QString & localName,
- const QString &)
+ virtual bool endElement(const QString&,
+ const QString& localName,
+ const QString&)
{
if (localName == "wpt") {
state = stateStack.takeLast();
wptList << currentWpt;
- }
- else if (localName == "ele" && state == e_wpt) {
+ } else if (localName == "ele" && state == e_wpt) {
currentWpt.setElevation(textChars.toDouble());
- }
- else if (localName == "name" && state == e_wpt) {
+ } else if (localName == "name" && state == e_wpt) {
currentWpt.setName(textChars);
- }
- else if (localName == "cmt" && state == e_wpt) {
+ } else if (localName == "cmt" && state == e_wpt) {
currentWpt.setComment(textChars);
- }
- else if (localName == "desc" && state == e_wpt) {
+ } else if (localName == "desc" && state == e_wpt) {
currentWpt.setDescription(textChars);
- }
- else if (localName == "sym" && state == e_wpt) {
+ } else if (localName == "sym" && state == e_wpt) {
currentWpt.setSymbol(textChars);
}
else if (localName == "trkpt") {
state = stateStack.takeLast();
currentTrkSeg.addPoint(currentTrkPt);
- }
- else if (localName == "ele" && state == e_trkpt) {
+ } else if (localName == "ele" && state == e_trkpt) {
currentTrkPt.setElevation(textChars.toDouble());
- }
- else if (localName == "time" && state == e_trkpt) {
+ } else if (localName == "time" && state == e_trkpt) {
currentTrkPt.setDateTime(decodeDateTime(textChars));
}
else if (localName == "trk") {
state = stateStack.takeLast();
- if (!trackIsEmpty(currentTrk))
- trkList << currentTrk;
+ if (!trackIsEmpty(currentTrk)) {
+ trkList << currentTrk;
+ }
}
else if (localName == "name" && state == e_trk) {
currentTrk.setName(textChars);
- }
- else if (localName == "number" && state == e_trk) {
+ } else if (localName == "number" && state == e_trk) {
currentTrk.setNumber(textChars.toInt());
}
else if (localName == "rte") {
state = stateStack.takeLast();
- if (currentRte.getRoutePoints().size()>=2)
- rteList << currentRte;
+ if (currentRte.getRoutePoints().size()>=2) {
+ rteList << currentRte;
+ }
}
else if (localName == "rtept") {
return true;
};
- virtual bool characters(const QString &x)
+ virtual bool characters(const QString& x)
{
textChars = x;
return true;
//------------------------------------------------------------------------
-bool Gpx::read(const QString & fileName)
+bool Gpx::read(const QString& fileName)
{
QFile file(fileName);
- if (!file.open(QIODevice::ReadOnly))
+ if (!file.open(QIODevice::ReadOnly)) {
return false;
+ }
QXmlInputSource xmlIn(&file);
tracks = gpxHandler.trkList;
routes = gpxHandler.rteList;
return true;
- }
- else
+ } else {
return false;
+ }
}
#include "latlng.h"
//------------------------------------------------------------------------
-class GpxItem {
- public:
- GpxItem(): visible(true) {};
- GpxItem(bool visible ): visible(visible) {};
-
- void setVisible(bool b) { visible = b; };
- bool getVisible() const { return visible;};
-
- protected:
- bool visible;
+class GpxItem
+{
+public:
+ GpxItem(): visible(true) {};
+ GpxItem(bool visible): visible(visible) {};
+
+ void setVisible(bool b)
+ {
+ visible = b;
+ };
+ bool getVisible() const
+ {
+ return visible;
+ };
+
+protected:
+ bool visible;
};
//------------------------------------------------------------------------
class GpxRoutePoint: public GpxItem
{
- public:
+public:
GpxRoutePoint(): GpxItem(), location(LatLng()), name(QString())
- {
- };
- void setLocation(const LatLng& pt) { location = pt; };
- LatLng getLocation() const { return location; };
+ {
+ };
+ void setLocation(const LatLng& pt)
+ {
+ location = pt;
+ };
+ LatLng getLocation() const
+ {
+ return location;
+ };
- void setName(const QString &s) { name = s; };
- QString getName () const { return name; };
+ void setName(const QString& s)
+ {
+ name = s;
+ };
+ QString getName() const
+ {
+ return name;
+ };
- private:
+private:
LatLng location;
QString name;
};
//------------------------------------------------------------------------
class GpxRoute: public GpxItem
{
- public:
+public:
GpxRoute(): GpxItem(),name(QString()), cachedLength(-1) {};
- GpxRoute(const GpxRoute &c)
- :GpxItem(c.visible),
- name(c.name), cachedLength(c.cachedLength)
- {
- routePoints.clear();
- foreach (GpxRoutePoint sg, c.routePoints)
- routePoints << sg;
- }
- GpxRoute & operator = (const GpxRoute &c)
- {
- visible = c.visible;
- name = c.name;
- cachedLength = c.cachedLength;
- routePoints.clear();
- foreach (GpxRoutePoint sg, c.routePoints) {
- routePoints << sg;
- }
- return *this;
+ GpxRoute(const GpxRoute& c)
+ :GpxItem(c.visible),
+ name(c.name), cachedLength(c.cachedLength)
+ {
+ routePoints.clear();
+ foreach (GpxRoutePoint sg, c.routePoints) {
+ routePoints << sg;
}
+ }
+ GpxRoute& operator = (const GpxRoute& c)
+ {
+ visible = c.visible;
+ name = c.name;
+ cachedLength = c.cachedLength;
+ routePoints.clear();
+ foreach (GpxRoutePoint sg, c.routePoints) {
+ routePoints << sg;
+ }
+ return *this;
+ }
double length() const
{
- if (cachedLength >=0.0)
+ if (cachedLength >=0.0) {
return cachedLength;
+ }
LatLng prevPt;
bool first = true;
double dist = 0.0;
foreach (GpxRoutePoint pt, routePoints) {
if (first) {
- prevPt = pt.getLocation();
- first = false;
- }
- else {
- LatLng thisPt = pt.getLocation();
- dist += prevPt.haversineDistance(thisPt);
- prevPt = thisPt;
+ prevPt = pt.getLocation();
+ first = false;
+ } else {
+ LatLng thisPt = pt.getLocation();
+ dist += prevPt.haversineDistance(thisPt);
+ prevPt = thisPt;
}
}
- double *dptr = (double *)(&cachedLength); // big cheat
+ double* dptr = (double*)(&cachedLength); // big cheat
*dptr = dist;
return cachedLength;
}
-
- void setName(const QString &s) { name = s; };
- QString getName() const { return name; };
- void clear() { routePoints.clear(); };
- void addPoint(const GpxRoutePoint &pt) {
+ void setName(const QString& s)
+ {
+ name = s;
+ };
+ QString getName() const
+ {
+ return name;
+ };
+
+ void clear()
+ {
+ routePoints.clear();
+ };
+ void addPoint(const GpxRoutePoint& pt)
+ {
routePoints << pt;
}
- const QList<GpxRoutePoint> & getRoutePoints() const { return routePoints; };
+ const QList<GpxRoutePoint>& getRoutePoints() const
+ {
+ return routePoints;
+ };
- private:
+private:
QString name;
QList <GpxRoutePoint> routePoints;
double cachedLength;
//------------------------------------------------------------------------
class GpxTrackPoint: public GpxItem
{
- public:
- GpxTrackPoint(): GpxItem(), location(LatLng()), elevation(0), dateTime(QDateTime())
- {
- };
- void setLocation(const LatLng& pt) { location = pt; };
- LatLng getLocation() const { return location; };
+public:
+ GpxTrackPoint(): GpxItem(), location(LatLng()), elevation(0), dateTime(QDateTime())
+ {
+ };
+ void setLocation(const LatLng& pt)
+ {
+ location = pt;
+ };
+ LatLng getLocation() const
+ {
+ return location;
+ };
- void setElevation(double e) { elevation = e; };
- double getElevation () const { return elevation; };
+ void setElevation(double e)
+ {
+ elevation = e;
+ };
+ double getElevation() const
+ {
+ return elevation;
+ };
- void setDateTime(const QDateTime &dt) { dateTime = dt; };
- QDateTime getDateTime() const { return dateTime; };
+ void setDateTime(const QDateTime& dt)
+ {
+ dateTime = dt;
+ };
+ QDateTime getDateTime() const
+ {
+ return dateTime;
+ };
- private:
+private:
LatLng location;
double elevation;
QDateTime dateTime;
//------------------------------------------------------------------------
class GpxTrackSegment: public GpxItem
{
- public:
+public:
GpxTrackSegment() {};
- GpxTrackSegment(const GpxTrackSegment &c): GpxItem(c.visible) {
+ GpxTrackSegment(const GpxTrackSegment& c): GpxItem(c.visible)
+ {
trackPoints.clear();
- foreach (GpxTrackPoint pt, c.trackPoints)
+ foreach (GpxTrackPoint pt, c.trackPoints) {
trackPoints << pt;
+ }
}
- GpxTrackSegment & operator = (const GpxTrackSegment &c) {
+ GpxTrackSegment& operator = (const GpxTrackSegment& c)
+ {
visible = c.visible;
trackPoints.clear();
- foreach (GpxTrackPoint pt, c.trackPoints)
+ foreach (GpxTrackPoint pt, c.trackPoints) {
trackPoints << pt;
+ }
return *this;
}
- void addPoint(const GpxTrackPoint & pt) {
+ void addPoint(const GpxTrackPoint& pt)
+ {
trackPoints << pt;
}
- void clear() { trackPoints.clear(); };
- const QList<GpxTrackPoint> & getTrackPoints() const { return trackPoints; };
+ void clear()
+ {
+ trackPoints.clear();
+ };
+ const QList<GpxTrackPoint>& getTrackPoints() const
+ {
+ return trackPoints;
+ };
- private:
+private:
QList <GpxTrackPoint> trackPoints;
};
//------------------------------------------------------------------------
class GpxTrack: public GpxItem
{
- public:
+public:
GpxTrack(): GpxItem(), number(1), name(QString()), comment(QString()), description(QString()), cachedLength(-1.0) {};
- GpxTrack(const GpxTrack &c)
- :GpxItem(c.visible),
- number(c.number),
- name(c.name),
- comment(c.comment),
- description (c.description),
- cachedLength(c.cachedLength)
- {
- trackSegments.clear();
- foreach (GpxTrackSegment sg, c.trackSegments)
- trackSegments << sg;
- }
- GpxTrack & operator = (const GpxTrack &c)
- {
- visible = c.visible;
- number = c.number;
- name = c.name;
- comment = c.comment;
- description = c.description;
- cachedLength = c.cachedLength;
- trackSegments.clear();
- foreach (GpxTrackSegment sg, c.trackSegments) {
- trackSegments << sg;
- }
- return *this;
+ GpxTrack(const GpxTrack& c)
+ :GpxItem(c.visible),
+ number(c.number),
+ name(c.name),
+ comment(c.comment),
+ description(c.description),
+ cachedLength(c.cachedLength)
+ {
+ trackSegments.clear();
+ foreach (GpxTrackSegment sg, c.trackSegments) {
+ trackSegments << sg;
+ }
+ }
+ GpxTrack& operator = (const GpxTrack& c)
+ {
+ visible = c.visible;
+ number = c.number;
+ name = c.name;
+ comment = c.comment;
+ description = c.description;
+ cachedLength = c.cachedLength;
+ trackSegments.clear();
+ foreach (GpxTrackSegment sg, c.trackSegments) {
+ trackSegments << sg;
}
+ return *this;
+ }
- void setNumber(int n) { number = n; };
- int getNumber() const { return number; };
+ void setNumber(int n)
+ {
+ number = n;
+ };
+ int getNumber() const
+ {
+ return number;
+ };
- void setName(const QString &s) { name = s; };
- QString getName() const { return name; };
+ void setName(const QString& s)
+ {
+ name = s;
+ };
+ QString getName() const
+ {
+ return name;
+ };
- void setComment(const QString &s) { comment = s; };
- QString getComment() const { return comment; };
+ void setComment(const QString& s)
+ {
+ comment = s;
+ };
+ QString getComment() const
+ {
+ return comment;
+ };
- void setDescription(const QString &s) { description = s; };
- QString getDescription() const { return description; };
+ void setDescription(const QString& s)
+ {
+ description = s;
+ };
+ QString getDescription() const
+ {
+ return description;
+ };
- void clear() { trackSegments.clear(); };
- void addSegment(const GpxTrackSegment &seg) {
+ void clear()
+ {
+ trackSegments.clear();
+ };
+ void addSegment(const GpxTrackSegment& seg)
+ {
trackSegments << seg;
}
- const QList<GpxTrackSegment> & getTrackSegments() const { return trackSegments; };
+ const QList<GpxTrackSegment>& getTrackSegments() const
+ {
+ return trackSegments;
+ };
double length() const
{
- if (cachedLength >=0.0)
+ if (cachedLength >=0.0) {
return cachedLength;
+ }
LatLng prevPt;
bool first = true;
double dist = 0.0;
foreach (GpxTrackSegment seg, trackSegments) {
foreach (GpxTrackPoint pt, seg.getTrackPoints()) {
- if (first) {
- prevPt = pt.getLocation();
- first = false;
- }
- else {
- LatLng thisPt = pt.getLocation();
- dist += prevPt.haversineDistance(thisPt);
- prevPt = thisPt;
- }
+ if (first) {
+ prevPt = pt.getLocation();
+ first = false;
+ } else {
+ LatLng thisPt = pt.getLocation();
+ dist += prevPt.haversineDistance(thisPt);
+ prevPt = thisPt;
+ }
}
}
- double *dptr = (double *)(&cachedLength); // big cheat
+ double* dptr = (double*)(&cachedLength); // big cheat
*dptr = dist;
return cachedLength;
}
- private:
+private:
int number;
QString name;
QString comment;
//------------------------------------------------------------------------
class GpxWaypoint: public GpxItem
{
- public:
- GpxWaypoint(): GpxItem(),
+public:
+ GpxWaypoint(): GpxItem(),
location_(LatLng(0, 0)),
- elevation_ (-1.0E-100),
+ elevation_(-1.0E-100),
name_(QString()),
comment_(QString()),
description_(QString()),
symbol_(QString())
- {};
-
- void setLocation(const LatLng& pt) { location_ = pt; };
- LatLng getLocation() const { return location_; };
+ {};
- void setElevation(double e) { elevation_ = e; };
- double getElevation () const { return elevation_; };
+ void setLocation(const LatLng& pt)
+ {
+ location_ = pt;
+ };
+ LatLng getLocation() const
+ {
+ return location_;
+ };
- void setName(const QString &s) { name_ = s; };
- QString getName() const { return name_; };
+ void setElevation(double e)
+ {
+ elevation_ = e;
+ };
+ double getElevation() const
+ {
+ return elevation_;
+ };
- void setComment(const QString &s) { comment_ = s; };
- QString getComment() const { return comment_; };
+ void setName(const QString& s)
+ {
+ name_ = s;
+ };
+ QString getName() const
+ {
+ return name_;
+ };
- void setDescription(const QString &s) { description_ = s; };
- QString getDescription() const { return description_; };
+ void setComment(const QString& s)
+ {
+ comment_ = s;
+ };
+ QString getComment() const
+ {
+ return comment_;
+ };
+
+ void setDescription(const QString& s)
+ {
+ description_ = s;
+ };
+ QString getDescription() const
+ {
+ return description_;
+ };
- void setSymbol(const QString &s) { symbol_ = s; };
- QString getSymbol() const { return symbol_; };
+ void setSymbol(const QString& s)
+ {
+ symbol_ = s;
+ };
+ QString getSymbol() const
+ {
+ return symbol_;
+ };
- private:
+private:
LatLng location_;
double elevation_;
QString name_;
};
//------------------------------------------------------------------------
-class Gpx {
+class Gpx
+{
public:
Gpx() {};
- bool read(const QString & fileName);
-
- QList <GpxWaypoint> &getWaypoints() { return wayPoints; }; // nonconst
- QList <GpxTrack> &getTracks() { return tracks; };
- QList <GpxRoute> &getRoutes() { return routes; };
+ bool read(const QString& fileName);
- const QList <GpxWaypoint> &getWaypoints() const { return wayPoints; };
- const QList <GpxTrack> &getTracks() const { return tracks; };
- const QList <GpxRoute> &getRoutes() const { return routes; };
+ QList <GpxWaypoint>& getWaypoints()
+ {
+ return wayPoints;
+ }; // nonconst
+ QList <GpxTrack>& getTracks()
+ {
+ return tracks;
+ };
+ QList <GpxRoute>& getRoutes()
+ {
+ return routes;
+ };
+
+ const QList <GpxWaypoint>& getWaypoints() const
+ {
+ return wayPoints;
+ };
+ const QList <GpxTrack>& getTracks() const
+ {
+ return tracks;
+ };
+ const QList <GpxRoute>& getRoutes() const
+ {
+ return routes;
+ };
- private:
+private:
QList <GpxWaypoint> wayPoints;
QList <GpxTrack> tracks;
QList <GpxRoute> routes;
#include "format.h"
//------------------------------------------------------------------------
-void ShowHelp(const QString &urlIn)
+void ShowHelp(const QString& urlIn)
{
QString url = urlIn;
#define HELP_H
#include <QString>
-extern void ShowHelp(const QString & name);
+extern void ShowHelp(const QString& name);
#endif
*
* @sa ArcInRadians
*/
-static double DistanceInMeters(const LatLng& from, const LatLng& to) {
+static double DistanceInMeters(const LatLng& from, const LatLng& to)
+{
return EARTH_RADIUS_IN_METERS*ArcInRadians(from, to);
}
//------------------------------------------------------------------------
-double LatLng::haversineDistance(const LatLng &other) const
+double LatLng::haversineDistance(const LatLng& other) const
{
return DistanceInMeters(*this, other);
}
//------------------------------------------------------------------------
class LatLng
{
- public:
- LatLng(): _lat(0), _lng(0) {};
- LatLng(double lat, double lng): _lat(lat), _lng(lng) {};
- double lat() const { return _lat; }
- double lng() const { return _lng; }
- double haversineDistance(const LatLng &other) const;
-
- private:
+public:
+ LatLng(): _lat(0), _lng(0) {};
+ LatLng(double lat, double lng): _lat(lat), _lng(lng) {};
+ double lat() const
+ {
+ return _lat;
+ }
+ double lng() const
+ {
+ return _lng;
+ }
+ double haversineDistance(const LatLng& other) const;
+
+private:
double _lat;
double _lng;
};
#include "gmapdlg.h"
#ifdef _WIN32
-const char *pathSeparator = ";";
+const char* pathSeparator = ";";
#else
-const char *pathSeparator = ":";
+const char* pathSeparator = ":";
#endif
#if defined (Q_OS_MAC)
#endif
//------------------------------------------------------------------------
-int main(int argc, char**argv)
+int main(int argc, char** argv)
{
// MIN_QT_VERSION in configure.ac should correspond to the QT_VERSION_CHECK arguments in main.cc and gui/main.cc
#if (QT_VERSION < QT_VERSION_CHECK(5, 9, 0))
- #error this version of Qt is not supported.
+#error this version of Qt is not supported.
#endif
- QApplication *app;
+ QApplication* app;
app = new QApplication(argc, argv);
app->setWindowIcon(QIcon(":/images/appicon.png"));
QString newPath = "PATH=" + QApplication::applicationDirPath() +
- QString(pathSeparator) + getenv("PATH");
- char *newPathEnv = new char[newPath.length() + 1];
+ QString(pathSeparator) + getenv("PATH");
+ char* newPathEnv = new char[newPath.length() + 1];
strcpy(newPathEnv, newPath.toStdString().c_str());
putenv(newPathEnv);
{
QProcess babel;
babel.start("gpsbabel", QStringList() << "-V");
- if (!babel.waitForStarted())
+ if (!babel.waitForStarted()) {
return QString();
+ }
babel.closeWriteChannel();
- if (!babel.waitForFinished())
+ if (!babel.waitForFinished()) {
return QString();
+ }
QString str = babel.readAll();
isBeta_ = str.contains("-beta");
bool MainWindow::allowBetaUpgrades()
{
// If this is a beta version (which means the user consciously downloaded
- // it and decided to be on the beta track or the user has ticked the
+ // it and decided to be on the beta track or the user has ticked the
// 'suggest beta upgrade' box, allow betas to be suggested for installation.
return isBeta_ || babelData_.allowBetaUpgrades_;
}
QVariant default_value = option.getDefaultValue();
if (option.getSelected()) {
// For OPTbool, 'selected' is the key, not value.
- if (option.getType() == FormatOption::OPTbool) {
- // Only write "foo=1" if that's not already the default.
- if (default_value != "1") {
+ if (option.getType() == FormatOption::OPTbool) {
+ // Only write "foo=1" if that's not already the default.
+ if (default_value != "1") {
str += "," + option.getName() + "=1";
}
} else {
if (option.getType() == FormatOption::OPTbool &&
default_value != "0" &&
default_value != "") {
- str += "," + option.getName() + "=0";
- }
+ str += "," + option.getName() + "=0";
}
}
+ }
return str;
}
connect(ui_.actionPreferences, SIGNAL(triggered()), this, SLOT(preferencesActionX()));
connect(ui_.inputFormatCombo, SIGNAL(currentIndexChanged(int)),
- this, SLOT(inputFormatChanged(int)));
+ this, SLOT(inputFormatChanged(int)));
connect(ui_.outputFormatCombo, SIGNAL(currentIndexChanged(int)),
- this, SLOT(outputFormatChanged(int)));
+ this, SLOT(outputFormatChanged(int)));
connect(ui_.inputOptionsBtn, SIGNAL(clicked()),
- this, SLOT(inputOptionButtonClicked()));
- connect(ui_.outputOptionsBtn , SIGNAL(clicked()),
- this, SLOT(outputOptionButtonClicked()));
- connect(ui_.moreOptionButton , SIGNAL(clicked()),
- this, SLOT(moreOptionButtonClicked()));
+ this, SLOT(inputOptionButtonClicked()));
+ connect(ui_.outputOptionsBtn, SIGNAL(clicked()),
+ this, SLOT(outputOptionButtonClicked()));
+ connect(ui_.moreOptionButton, SIGNAL(clicked()),
+ this, SLOT(moreOptionButtonClicked()));
connect(ui_.buttonBox, SIGNAL(accepted()), this, SLOT(applyActionX()));
connect(ui_.buttonBox, SIGNAL(rejected()), this, SLOT(closeActionX()));
//------------------------------------------------------------------------
MainWindow::~MainWindow()
{
- if (upgrade)
+ if (upgrade) {
delete upgrade;
+ }
}
//------------------------------------------------------------------------
-// Dynamic language switching courtesy of
+// Dynamic language switching courtesy of
// http://developer.qt.nokia.com/wiki/How_to_create_a_multi_language_application
-// We create the menu entries dynamically, dependant on the existing
+// We create the menu entries dynamically, dependant on the existing
// translations.
#if FAKE_LANGUAGE_MENU
void MainWindow::createLanguageMenu(void)
{
- QActionGroup* langGroup = new QActionGroup(ui.menuHelp);
- langGroup->setExclusive(true);
- connect(langGroup, SIGNAL(triggered(QAction *)), this, SLOT(slotLanguageChanged(QAction *)));
+ QActionGroup* langGroup = new QActionGroup(ui.menuHelp);
+ langGroup->setExclusive(true);
+ connect(langGroup, SIGNAL(triggered(QAction*)), this, SLOT(slotLanguageChanged(QAction*)));
- // format systems language
- QString defaultLocale = QLocale::system().name(); // e.g. "de_DE"
- defaultLocale.truncate(defaultLocale.lastIndexOf('_')); // e.g. "de"
+ // format systems language
+ QString defaultLocale = QLocale::system().name(); // e.g. "de_DE"
+ defaultLocale.truncate(defaultLocale.lastIndexOf('_')); // e.g. "de"
- QDir dir(langPath);
- QStringList fileNames = dir.entryList(QStringList("GPSBabelFE*.qm"));
+ QDir dir(langPath);
+ QStringList fileNames = dir.entryList(QStringList("GPSBabelFE*.qm"));
- for (int i = 0; i < fileNames.size(); ++i) {
- // get locale extracted by filename
- QString locale;
- locale = fileNames[i]; // "TranslationExample_de.qm"
- locale.truncate(locale.lastIndexOf('.')); // "TranslationExample_de"
- locale.remove(0, locale.indexOf('_') + 1); // "de"
+ for (int i = 0; i < fileNames.size(); ++i) {
+ // get locale extracted by filename
+ QString locale;
+ locale = fileNames[i]; // "TranslationExample_de.qm"
+ locale.truncate(locale.lastIndexOf('.')); // "TranslationExample_de"
+ locale.remove(0, locale.indexOf('_') + 1); // "de"
- QString lang = QLocale::languageToString(QLocale(locale).language());
+ QString lang = QLocale::languageToString(QLocale(locale).language());
- QAction *action = new QAction(lang, this);
- action->setCheckable(true);
- action->setData(locale);
+ QAction* action = new QAction(lang, this);
+ action->setCheckable(true);
+ action->setData(locale);
- ui.menuHelp->addAction(action);
- langGroup->addAction(action);
+ ui.menuHelp->addAction(action);
+ langGroup->addAction(action);
- // set default translators and language checked
- if (defaultLocale == locale) {
- action->setChecked(true);
- }
+ // set default translators and language checked
+ if (defaultLocale == locale) {
+ action->setChecked(true);
}
+ }
}
#endif // FAKE_LANGUAGE_MENU
QString full_filename(langPath_ + "/" + filename);
// load the new translator
- if (translator.load(full_filename))
+ if (translator.load(full_filename)) {
qApp->installTranslator(&translator);
+ }
}
void MainWindow::loadLanguage(const QString& rLanguage)
void MainWindow::changeEvent(QEvent* event)
{
- if (0 != event) {
- switch(event->type()) {
- // This event is sent if a translator is loaded.
- case QEvent::LanguageChange:
- ui_.retranslateUi(this);
- break;
- // This event is sent if the system language changes.
- case QEvent::LocaleChange:
- {
- QString locale = QLocale::system().name();
- locale.truncate(locale.lastIndexOf('_'));
- loadLanguage(locale);
- }
- break;
- default:
- break;
- }
+ if (0 != event) {
+ switch (event->type()) {
+ // This event is sent if a translator is loaded.
+ case QEvent::LanguageChange:
+ ui_.retranslateUi(this);
+ break;
+ // This event is sent if the system language changes.
+ case QEvent::LocaleChange: {
+ QString locale = QLocale::system().name();
+ locale.truncate(locale.lastIndexOf('_'));
+ loadLanguage(locale);
}
-
- QMainWindow::changeEvent(event);
+ break;
+ default:
+ break;
+ }
+ }
+
+ QMainWindow::changeEvent(event);
}
//------------------------------------------------------------------------
-void MainWindow::loadInputDeviceNameCombo(const QString &format)
+void MainWindow::loadInputDeviceNameCombo(const QString& format)
{
ui_.inputDeviceNameCombo->clear();
- // Later, we can probe the system for multiple USB devices and populate
+ // Later, we can probe the system for multiple USB devices and populate
// here.
- if (formatSupportsUSB(format))
+ if (formatSupportsUSB(format)) {
ui_.inputDeviceNameCombo->addItem("usb:");
- if (formatSupportsSerial(format))
+ }
+ if (formatSupportsSerial(format)) {
osLoadDeviceNameCombos(ui_.inputDeviceNameCombo);
+ }
// If only one choice, just disable it.
ui_.inputDeviceNameCombo->setEnabled(ui_.inputDeviceNameCombo->count() > 1);
}
//------------------------------------------------------------------------
-void MainWindow::loadOutputDeviceNameCombo(const QString &format)
+void MainWindow::loadOutputDeviceNameCombo(const QString& format)
{
ui_.outputDeviceNameCombo->clear();
- // Later, we can probe the system for multiple USB devices and populate
+ // Later, we can probe the system for multiple USB devices and populate
// here.
- if (formatSupportsUSB(format))
+ if (formatSupportsUSB(format)) {
ui_.outputDeviceNameCombo->addItem("usb:");
- if (formatSupportsSerial(format))
+ }
+ if (formatSupportsSerial(format)) {
osLoadDeviceNameCombos(ui_.outputDeviceNameCombo);
+ }
// If only one choice, just disable it.
ui_.outputDeviceNameCombo->setEnabled(ui_.outputDeviceNameCombo->count() > 1);
}
ui_.inputFormatCombo->clear();
for (int i=0; i<indices.size(); i++) {
int k = indices[i];
- if (!formatList_[k].isHidden())
+ if (!formatList_[k].isHidden()) {
ui_.inputFormatCombo->addItem(formatList_[k].getDescription(), QVariant(k));
+ }
}
setComboToFormat(ui_.inputFormatCombo, fmt, true);
fmtChgInterlock_ = false;
ui_.inputFormatCombo->clear();
for (int i=0; i<indices.size(); i++) {
int k = indices[i];
- if (!formatList_[k].isHidden())
+ if (!formatList_[k].isHidden()) {
ui_.inputFormatCombo->addItem(formatList_[k].getDescription(), QVariant(k));
+ }
}
setComboToFormat(ui_.inputFormatCombo, fmt, false);
fmtChgInterlock_ = false;
ui_.outputFormatCombo->clear();
for (int i=0; i<indices.size(); i++) {
int k = indices[i];
- if (!formatList_[k].isHidden())
+ if (!formatList_[k].isHidden()) {
ui_.outputFormatCombo->addItem(formatList_[k].getDescription(), QVariant(k));
+ }
}
setComboToFormat(ui_.outputFormatCombo, fmt, true);
- }
- else {
+ } else {
ui_.outputStackedWidget->setCurrentWidget(ui_.outputFilePage);
ui_.outputFilePage->setEnabled(false);
}
ui_.outputFormatCombo->clear();
for (int i=0; i<indices.size(); i++) {
int k = indices[i];
- if (!formatList_[k].isHidden())
+ if (!formatList_[k].isHidden()) {
ui_.outputFormatCombo->addItem(formatList_[k].getDescription(), QVariant(k));
+ }
}
setComboToFormat(ui_.outputFormatCombo, fmt, false);
- }
- else {
+ } else {
ui_.outputStackedWidget->setCurrentWidget(ui_.outputDevicePage);
ui_.outputDevicePage->setEnabled(false);
}
if (extensions.size() > 0 && !extensions[0].isEmpty()) {
str += " (";
for (int i=0; i<extensions.size(); i++) {
- if (i!= 0)
+ if (i!= 0) {
str += " ";
+ }
str += "*." + extensions[i];
}
str += ");;";
return str;
}
//------------------------------------------------------------------------
-QString MainWindow::ensureExtensionPresent(const QString &name, int idx)
+QString MainWindow::ensureExtensionPresent(const QString& name, int idx)
{
QString outname = name;
if (QFileInfo(name).suffix().length() == 0) {
QStringList extensions = formatList_[idx].getExtensions();
- if (extensions.size() > 0 && !extensions[0].isEmpty())
+ if (extensions.size() > 0 && !extensions[0].isEmpty()) {
outname += "." + extensions[0];
+ }
}
return outname;
}
//------------------------------------------------------------------------
-bool MainWindow::filterForFormatIncludes(int idx, const QString &fmt)
+bool MainWindow::filterForFormatIncludes(int idx, const QString& fmt)
{
QStringList extensions = formatList_[idx].getExtensions();
for (int i=0; i<extensions.size(); i++) {
- if (fmt == extensions[i])
+ if (fmt == extensions[i]) {
return true;
+ }
}
return false;
}
//------------------------------------------------------------------------
-int MainWindow::currentComboFormatIndex(QComboBox *comboBox)
+int MainWindow::currentComboFormatIndex(QComboBox* comboBox)
{
int idx = comboBox->currentIndex();
if (idx<0 || idx >= comboBox->count()) {
QStringList userList =
QFileDialog::getOpenFileNames(0, tr("Select one or more input files"),
- startFile,
- filterForFormat(idx));
+ startFile,
+ filterForFormat(idx));
if (userList.size()) {
babelData_.inputBrowse_ = userList[0];
babelData_.inputFileNames_ = userList;
QString str;
for (int i=0; i<babelData_.inputFileNames_.size(); i++) {
- if (i != 0)
+ if (i != 0) {
str += ", ";
+ }
str += "\"" + babelData_.inputFileNames_[i] + "\"";
}
ui_.inputFileNameText->setText(str);
QString str =
QFileDialog::getSaveFileName(0, tr("Output File Name"),
- startFile,
- filterForFormat(idx));
+ startFile,
+ filterForFormat(idx));
if (str.length() != 0) {
str = ensureExtensionPresent(str, idx);
babelData_.outputBrowse_ = str;
{
QList<int>indices;
for (int i=0; i<formatList_.size(); i++) {
- if (formatList_[i].isReadSomething() && formatList_[i].isFileFormat())
+ if (formatList_[i].isReadSomething() && formatList_[i].isFileFormat()) {
indices<<i;
+ }
}
return indices;
}
{
QList<int>indices;
for (int i=0; i<formatList_.size(); i++) {
- if (formatList_[i].isReadSomething() && formatList_[i].isDeviceFormat())
+ if (formatList_[i].isReadSomething() && formatList_[i].isDeviceFormat()) {
indices<<i;
+ }
}
return indices;
}
{
QList<int>indices;
for (int i=0; i<formatList_.size(); i++) {
- if (formatList_[i].isWriteSomething() && formatList_[i].isFileFormat())
+ if (formatList_[i].isWriteSomething() && formatList_[i].isFileFormat()) {
indices<<i;
+ }
}
return indices;
}
{
QList<int>indices;
for (int i=0; i<formatList_.size(); i++) {
- if (formatList_[i].isWriteSomething() && formatList_[i].isDeviceFormat())
+ if (formatList_[i].isWriteSomething() && formatList_[i].isDeviceFormat()) {
indices<<i;
+ }
}
return indices;
}
{
if (!FormatLoad().getFormats(formatList_)) {
QMessageBox::information(0, QString(appName),
- tr("Error reading format configuration. "
- "Check that the backend program \"gpsbabel\" is properly installed "
- "and is in the current PATH\n\n"
- "This program cannot continue."));
- exit(1);
+ tr("Error reading format configuration. "
+ "Check that the backend program \"gpsbabel\" is properly installed "
+ "and is in the current PATH\n\n"
+ "This program cannot continue."));
+ exit(1);
}
if (inputFileFormatIndices().size() == 0 ||
inputDeviceFormatIndices().size() == 0 ||
outputFileFormatIndices().size() == 0 ||
outputDeviceFormatIndices().size() == 0) {
QMessageBox::information(0, QString(appName),
- tr("Some file/device formats were not found during initialization. "
- "Check that the backend program \"gpsbabel\" is properly installed "
- "and is in the current PATH\n\n"
- "This program cannot continue."));
+ tr("Some file/device formats were not found during initialization. "
+ "Check that the backend program \"gpsbabel\" is properly installed "
+ "and is in the current PATH\n\n"
+ "This program cannot continue."));
exit(1);
}
}
}
//------------------------------------------------------------------------
-void MainWindow::setIndicatorLights(QLabel *label, const QString &type, int code)
+void MainWindow::setIndicatorLights(QLabel* label, const QString& type, int code)
{
label->setPixmap(lights_[code]);
QString s;
- switch (code)
- {
- default:
- case 0:
- s = tr("Input and output formats do not support %1").arg(type);
- break;
- case 1:
- s = tr("Input does not support %1; output format supports %1").arg(type);
- break;
- case 2:
- s = tr("Input format supports %1; output format does not support %1").arg(type);
- break;
- case 3:
- s = tr("Both input and output formats support %1").arg(type);
- break;
- }
+ switch (code) {
+ default:
+ case 0:
+ s = tr("Input and output formats do not support %1").arg(type);
+ break;
+ case 1:
+ s = tr("Input does not support %1; output format supports %1").arg(type);
+ break;
+ case 2:
+ s = tr("Input format supports %1; output format does not support %1").arg(type);
+ break;
+ case 3:
+ s = tr("Both input and output formats support %1").arg(type);
+ break;
+ }
label->setToolTip(s);
}
}
//------------------------------------------------------------------------
-void MainWindow::displayOptionsText(QLineEdit *le, QComboBox *combo, bool isInput)
+void MainWindow::displayOptionsText(QLineEdit* le, QComboBox* combo, bool isInput)
{
int fidx = combo->itemData(combo->currentIndex()).toInt();
- if (isInput)
+ if (isInput) {
le->setText(MakeOptionsNoLeadingComma(formatList_[fidx].getInputOptions()));
- else
+ } else {
le->setText(MakeOptionsNoLeadingComma(formatList_[fidx].getOutputOptions()));
+ }
}
//------------------------------------------------------------------------
-void MainWindow::setComboToFormat(QComboBox *comboBox, const QString &name, bool isFile)
+void MainWindow::setComboToFormat(QComboBox* comboBox, const QString& name, bool isFile)
{
int fidx = -1;
for (int i=0; i<formatList_.size(); i++) {
if (formatList_[i].getName() == name &&
- formatList_[i].isFileFormat() == isFile) {
+ formatList_[i].isFileFormat() == isFile) {
fidx = i;
break;
}
if (fidx >=0) {
for (int i=0; i<comboBox->count(); i++) {
if (comboBox->itemData(i).toInt() == fidx) {
- comboBox->setCurrentIndex(i);
- break;
+ comboBox->setCurrentIndex(i);
+ break;
}
}
}
}
//------------------------------------------------------------------------
-bool MainWindow::formatSupportsUSB(const QString &format)
+bool MainWindow::formatSupportsUSB(const QString& format)
{
- return (format == "garmin" || format == "delbin");
+ return (format == "garmin" || format == "delbin");
}
//------------------------------------------------------------------------
-bool MainWindow::formatSupportsSerial(const QString &format)
+bool MainWindow::formatSupportsSerial(const QString& format)
{
- return (format != "delbin");
+ return (format != "delbin");
}
//------------------------------------------------------------------------
void MainWindow::inputFormatChanged(int comboIdx)
{
- if (fmtChgInterlock_)
+ if (fmtChgInterlock_) {
return;
+ }
int fidx = ui_.inputFormatCombo->itemData(comboIdx).toInt();
ui_.inputOptionsBtn->setEnabled(formatList_[fidx].getInputOptions().size()>0);
displayOptionsText(ui_.inputOptionsText, ui_.inputFormatCombo, true);
crossCheckInOutFormats();
- if (ui_.inputFileOptBtn->isChecked())
+ if (ui_.inputFileOptBtn->isChecked()) {
babelData_.inputFileFormat_ =formatList_[fidx].getName();
- else
+ } else {
babelData_.inputDeviceFormat_ = formatList_[fidx].getName();
+ }
loadInputDeviceNameCombo(formatList_[fidx].getName());
}
//------------------------------------------------------------------------
void MainWindow::outputFormatChanged(int comboIdx)
{
- if (fmtChgInterlock_)
+ if (fmtChgInterlock_) {
return;
+ }
int fidx = ui_.outputFormatCombo->itemData(comboIdx).toInt();
ui_.outputOptionsBtn->setEnabled(formatList_[fidx].getOutputOptions().size()>0);
displayOptionsText(ui_.outputOptionsText, ui_.outputFormatCombo, false);
crossCheckInOutFormats();
- if (ui_.outputFileOptBtn->isChecked())
+ if (ui_.outputFileOptBtn->isChecked()) {
babelData_.outputFileFormat_ =formatList_[fidx].getName();
- else if (ui_.outputDeviceOptBtn->isChecked())
+ } else if (ui_.outputDeviceOptBtn->isChecked()) {
babelData_.outputDeviceFormat_ = formatList_[fidx].getName();
+ }
loadOutputDeviceNameCombo(formatList_[fidx].getName());
}
int fidx = currentComboFormatIndex(ui_.inputFormatCombo);
if (formatList_[fidx].getInputOptionsRef()->size() == 0) {
QMessageBox::information
- (0, appName,
- tr("There are no input options for format \"%1\"").arg(formatList_[fidx].getDescription()));
- }
- else {
+ (0, appName,
+ tr("There are no input options for format \"%1\"").arg(formatList_[fidx].getDescription()));
+ } else {
OptionsDlg optionDlg(0,
- formatList_[fidx].getName(),
- formatList_[fidx].getInputOptionsRef(),
- formatList_[fidx].getHtml());
+ formatList_[fidx].getName(),
+ formatList_[fidx].getInputOptionsRef(),
+ formatList_[fidx].getHtml());
optionDlg.setWindowTitle(QString(appName) + " - " + tr("Options for %1").arg(formatList_[fidx].getName()));
optionDlg.exec();
displayOptionsText(ui_.inputOptionsText, ui_.inputFormatCombo, true);
int fidx = currentComboFormatIndex(ui_.outputFormatCombo);
if (formatList_[fidx].getOutputOptionsRef()->size() == 0) {
QMessageBox::information
- (0, appName,
- tr("There are no output options for format \"%1\"").arg(formatList_[fidx].getDescription()));
- }
- else {
- OptionsDlg optionDlg(0,
- formatList_[fidx].getName(),
- formatList_[fidx].getOutputOptionsRef(),
- formatList_[fidx].getHtml());
+ (0, appName,
+ tr("There are no output options for format \"%1\"").arg(formatList_[fidx].getDescription()));
+ } else {
+ OptionsDlg optionDlg(0,
+ formatList_[fidx].getName(),
+ formatList_[fidx].getOutputOptionsRef(),
+ formatList_[fidx].getHtml());
optionDlg.setWindowTitle(QString(appName) + " - " + tr("Options for %1").arg(formatList_[fidx].getName()));
optionDlg.exec();
displayOptionsText(ui_.outputOptionsText, ui_.outputFormatCombo, false);
bool MainWindow::isOkToGo()
{
if (!((ui_.xlateWayPtsCk->isChecked() && ui_.xlateWayPtsCk->isEnabled()) ||
- (ui_.xlateRoutesCk->isChecked() && ui_.xlateRoutesCk->isEnabled()) ||
- (ui_.xlateTracksCk->isChecked() && ui_.xlateTracksCk->isEnabled()))) {
+ (ui_.xlateRoutesCk->isChecked() && ui_.xlateRoutesCk->isEnabled()) ||
+ (ui_.xlateTracksCk->isChecked() && ui_.xlateTracksCk->isEnabled()))) {
QMessageBox::information(0, QString(appName), tr("No valid waypoints/routes/tracks translation specified"));
return false;
}
if (babelData_.outputType_ == BabelData::noType_ && babelData_.previewGmap_ == false) {
QMessageBox::information(0, QString(appName), tr("No valid output specified"));
return false;
- }
- else if (babelData_.outputType_ == BabelData::fileType_ &&
- babelData_.outputFileName_.length() == 0) {
+ } else if (babelData_.outputType_ == BabelData::fileType_ &&
+ babelData_.outputFileName_.length() == 0) {
QMessageBox::information(0, QString(appName), tr("No output file specified"));
return false;
}
}
//------------------------------------------------------------------------
-bool MainWindow::runGpsbabel(const QStringList &args, QString &errorString,
- QString &outputString)
+bool MainWindow::runGpsbabel(const QStringList& args, QString& errorString,
+ QString& outputString)
{
- QProcess *proc = new QProcess(0);
+ QProcess* proc = new QProcess(0);
QString name = "gpsbabel";
proc->start(name, args);
- ProcessWaitDialog *waitDlg = new ProcessWaitDialog(0, proc);
+ ProcessWaitDialog* waitDlg = new ProcessWaitDialog(0, proc);
if (proc->state() == QProcess::NotRunning) {
errorString = QString(tr("Process \"%1\" did not start")).arg(name);
bool retStatus = false;
if (waitDlg->getExitedNormally()) {
exitCode = waitDlg->getExitCode();
- if (exitCode == 0)
+ if (exitCode == 0) {
retStatus = true;
- else {
+ } else {
errorString =
- QString(tr("Process exited unsucessfully with code %1"))
- .arg(exitCode);
+ QString(tr("Process exited unsucessfully with code %1"))
+ .arg(exitCode);
retStatus = false;
}
- }
- else {
+ } else {
retStatus = false;
errorString = waitDlg->getErrorString();
}
}
//------------------------------------------------------------------------
-int MainWindow::formatIndexFromName(bool isFile, const QString &nm)
+int MainWindow::formatIndexFromName(bool isFile, const QString& nm)
{
for (int i= 0; i<formatList_.size(); i++) {
- if (nm == formatList_[i].getName() && formatList_[i].isFileFormat() == isFile)
+ if (nm == formatList_[i].getName() && formatList_[i].isFileFormat() == isFile) {
return i;
+ }
}
return 0;
}
//------------------------------------------------------------------------
-QString MainWindow::charSetFromCombo(QComboBox *combo)
+QString MainWindow::charSetFromCombo(QComboBox* combo)
{
int i = combo->itemData((combo->currentIndex())).toInt();
- return (i >=0 ) ? charSets_[i] : QString();
+ return (i >=0) ? charSets_[i] : QString();
}
//------------------------------------------------------------------------
-void MainWindow::setComboToCharSet(QComboBox *combo, const QString &cset)
+void MainWindow::setComboToCharSet(QComboBox* combo, const QString& cset)
{
for (int i=0; i<charSets_.size(); i++) {
if (charSets_[i] == cset) {
void MainWindow::applyActionX()
{
getWidgetValues();
- if (!isOkToGo())
+ if (!isOkToGo()) {
return;
+ }
QStringList args;
- if (babelData_.debugLevel_ >=0) args << QString("-D%1").arg(babelData_.debugLevel_);
- if (babelData_.synthShortNames_) args << "-s";
+ if (babelData_.debugLevel_ >=0) {
+ args << QString("-D%1").arg(babelData_.debugLevel_);
+ }
+ if (babelData_.synthShortNames_) {
+ args << "-s";
+ }
Format ifmt = formatList_[currentComboFormatIndex(ui_.inputFormatCombo)];
Format ofmt = formatList_[currentComboFormatIndex(ui_.outputFormatCombo)];
- if (babelData_.xlateWayPts_ && ifmt.isReadWaypoints() && ofmt.isWriteWaypoints())
+ if (babelData_.xlateWayPts_ && ifmt.isReadWaypoints() && ofmt.isWriteWaypoints()) {
args << "-w";
- if (babelData_.xlateRoutes_ && ifmt.isReadRoutes() && ofmt.isWriteRoutes())
+ }
+ if (babelData_.xlateRoutes_ && ifmt.isReadRoutes() && ofmt.isWriteRoutes()) {
args << "-r";
- if (babelData_.xlateTracks_ && ifmt.isReadTracks() && ofmt.isWriteTracks())
+ }
+ if (babelData_.xlateTracks_ && ifmt.isReadTracks() && ofmt.isWriteTracks()) {
args << "-t";
+ }
// Input type, with options
bool iisFile = (babelData_.inputType_ == BabelData::fileType_);
int fidx = formatIndexFromName(iisFile, iisFile ?
- babelData_.inputFileFormat_ : babelData_.inputDeviceFormat_);
+ babelData_.inputFileFormat_ : babelData_.inputDeviceFormat_);
args << "-i";
args << (formatList_[fidx].getName() + MakeOptions(formatList_[fidx].getInputOptions()));
args << "-f" << babelData_.inputFileNames_[i];
read_use_count++;
}
- }
- else {
+ } else {
args << "-f" << babelData_.inputDeviceName_;
read_use_count++;
}
if (babelData_.outputType_ != BabelData::noType_) {
bool outIsFile = (babelData_.outputType_ == BabelData::fileType_);
fidx = formatIndexFromName(outIsFile, (outIsFile ?
- babelData_.outputFileFormat_ : babelData_.outputDeviceFormat_));
+ babelData_.outputFileFormat_ : babelData_.outputDeviceFormat_));
args << "-o";
args << (formatList_[fidx].getName() + MakeOptions(formatList_[fidx].getOutputOptions()));
// output file or device option
if (outIsFile) {
- if (babelData_.outputFileName_ != "")
- args << "-F" << babelData_.outputFileName_;
- }
- else if (babelData_.outputType_ == BabelData::deviceType_) {
+ if (babelData_.outputFileName_ != "") {
+ args << "-F" << babelData_.outputFileName_;
+ }
+ } else if (babelData_.outputType_ == BabelData::deviceType_) {
args << "-F" << babelData_.outputDeviceName_;
}
// GUI only ever writes a single file at a time.
QFile(tempName).remove();
this->show();
}
- }
- else
+ } else {
ui_.outputWindow->appendPlainText(tr("Error running gpsbabel: %1\n").arg(errorString));
+ }
}
//------------------------------------------------------------------------
if ((babelData_.runCount_ == 1) ||
((babelData_.runCount_ > 5) && (babelData_.donateSplashed_.daysTo(now) > 30))) {
Donate donate(0);
- if (babelData_.donateSplashed_.date() == QDate(2010,1,1))
+ if (babelData_.donateSplashed_.date() == QDate(2010,1,1)) {
donate.showNever(false);
+ }
donate.exec();
babelData_.donateSplashed_ = now;
}
}
//------------------------------------------------------------------------
-void MainWindow::dragEnterEvent(QDragEnterEvent *event)
+void MainWindow::dragEnterEvent(QDragEnterEvent* event)
{
event->acceptProposedAction();
}
-void MainWindow::dropEvent(QDropEvent *event)
+void MainWindow::dropEvent(QDropEvent* event)
{
foreach (QString format, event->mimeData()->formats()) {
if (format == "text/uri-list") {
}
}
//------------------------------------------------------------------------
-void MainWindow::setComboToDevice(QComboBox *comboBox, const QString &name)
+void MainWindow::setComboToDevice(QComboBox* comboBox, const QString& name)
{
for (int i=0; i<comboBox->count(); i++) {
if (comboBox->itemText(i) == name) {
QSettings settings;
babelData_.saveSettings(settings);
- for (int i=0; i<formatList_.size(); i++)
+ for (int i=0; i<formatList_.size(); i++) {
formatList_[i].saveSettings(settings);
- for (int i=0; i<filterData_.filters.size(); i++)
+ }
+ for (int i=0; i<filterData_.filters.size(); i++) {
filterData_.filters[i]->saveSettings(settings);
+ }
}
//------------------------------------------------------------------------
{
QSettings settings;
babelData_.restoreSettings(settings);
- for (int i=0; i<formatList_.size(); i++)
+ for (int i=0; i<formatList_.size(); i++) {
formatList_[i].restoreSettings(settings);
+ }
- for (int i=0; i<filterData_.filters.size(); i++)
+ for (int i=0; i<filterData_.filters.size(); i++) {
filterData_.filters[i]->restoreSettings(settings);
+ }
setWidgetValues();
}
void MainWindow::resetFormatDefaults()
{
int ret = QMessageBox::warning
- (this, QString(appName),
- tr("Are you sure you want to reset all format options to default values?"),
- QMessageBox::Yes | QMessageBox::No);
+ (this, QString(appName),
+ tr("Are you sure you want to reset all format options to default values?"),
+ QMessageBox::Yes | QMessageBox::No);
if (ret == QMessageBox::Yes) {
- for (int i=0; i<formatList_.size(); i++)
+ for (int i=0; i<formatList_.size(); i++) {
formatList_[i].setToDefault();
+ }
displayOptionsText(ui_.inputOptionsText, ui_.inputFormatCombo, true);
displayOptionsText(ui_.outputOptionsText, ui_.outputFormatCombo, false);
}
AdvDlg advDlg(0, babelData_.synthShortNames_,
babelData_.previewGmap_, babelData_.debugLevel_);
connect(advDlg.formatButton(), SIGNAL(clicked()),
- this, SLOT(resetFormatDefaults()));
+ this, SLOT(resetFormatDefaults()));
advDlg.exec();
}
//------------------------------------------------------------------------
//------------------------------------------------------------------------
void MainWindow::upgradeCheckActionX()
{
- upgrade->checkForUpgrade(babelVersion_,
- QDateTime(QDate(2000, 1, 1), QTime(0, 0)),
- allowBetaUpgrades());
+ upgrade->checkForUpgrade(babelVersion_,
+ QDateTime(QDate(2000, 1, 1), QTime(0, 0)),
+ allowBetaUpgrades());
}
//------------------------------------------------------------------------
{
bool filterActive = filterData_.getAllFilterStrings().size();
ui_.filterStatus->setEnabled(filterActive);
- if (filterActive)
+ if (filterActive) {
ui_.filterStatus->setToolTip(tr("One or more data filters are active"));
- else {
+ } else {
ui_.filterStatus->setToolTip(tr("No data filters are active"));
}
}
inputFileOptBtnClicked();
setComboToFormat(ui_.inputFormatCombo, babelData_.inputFileFormat_, true);
ui_.inputStackedWidget->setCurrentWidget(ui_.inputFilePage);
- }
- else {
+ } else {
ui_.inputDeviceOptBtn->setChecked(true);
inputDeviceOptBtnClicked();
setComboToFormat(ui_.inputFormatCombo, babelData_.inputDeviceFormat_, false);
outputFileOptBtnClicked();
setComboToFormat(ui_.outputFormatCombo, babelData_.outputFileFormat_, true);
ui_.outputStackedWidget->setCurrentWidget(ui_.outputFilePage);
- }
- else if (babelData_.outputType_ == BabelData::deviceType_) {
+ } else if (babelData_.outputType_ == BabelData::deviceType_) {
ui_.outputDeviceOptBtn->setChecked(true);
outputDeviceOptBtnClicked();
setComboToFormat(ui_.outputFormatCombo, babelData_.outputDeviceFormat_, false);
loadOutputDeviceNameCombo(babelData_.outputDeviceFormat_);
ui_.outputStackedWidget->setCurrentWidget(ui_.outputDevicePage);
- }
- else {
+ } else {
ui_.outputFileOptBtn->setChecked(false);
ui_.outputDeviceOptBtn->setChecked(false);
setComboToFormat(ui_.outputFormatCombo, babelData_.outputFileFormat_, true);
{
int comboIdx = ui_.inputFormatCombo->currentIndex();
int fidx = ui_.inputFormatCombo->itemData(comboIdx).toInt();
- if (ui_.inputFileOptBtn->isChecked()){
+ if (ui_.inputFileOptBtn->isChecked()) {
babelData_.inputType_ = BabelData::fileType_;
babelData_.inputFileFormat_ =formatList_[fidx].getName();
- }
- else {
+ } else {
babelData_.inputType_ = BabelData::deviceType_;
babelData_.inputDeviceFormat_ =formatList_[fidx].getName();
}
comboIdx = ui_.outputFormatCombo->currentIndex();
fidx = ui_.outputFormatCombo->itemData(comboIdx).toInt();
- if (ui_.outputFileOptBtn->isChecked()){
+ if (ui_.outputFileOptBtn->isChecked()) {
babelData_.outputType_ = BabelData::fileType_;
babelData_.outputFileFormat_ =formatList_[fidx].getName();
- }
- else if (ui_.outputDeviceOptBtn->isChecked()){
+ } else if (ui_.outputDeviceOptBtn->isChecked()) {
babelData_.outputType_ = BabelData::deviceType_;
babelData_.outputDeviceFormat_ =formatList_[fidx].getName();
- }
- else {
+ } else {
babelData_.outputType_ = BabelData::noType_;
}
babelData_.outputDeviceName_ = ui_.outputDeviceNameCombo->currentText();
#include <QTranslator>
-class MainWindow: public QMainWindow {
+class MainWindow: public QMainWindow
+{
Q_OBJECT
- public:
+public:
MainWindow(QWidget* parent);
~MainWindow();
void switchTranslator(QTranslator&, const QString&);
void createLanguageMenu();
QString filterForFormat(int idx);
- QString ensureExtensionPresent(const QString &nanme, int idx);
+ QString ensureExtensionPresent(const QString& nanme, int idx);
QString findBabelVersion();
- bool filterForFormatIncludes(int idx, const QString &s);
- int formatIndexFromName(bool isFile, const QString &);
+ bool filterForFormatIncludes(int idx, const QString& s);
+ int formatIndexFromName(bool isFile, const QString&);
QList<int>inputFileFormatIndices();
QList<int>inputDeviceFormatIndices();
QList<int>outputFileFormatIndices();
QList<int>outputDeviceFormatIndices();
- int currentComboFormatIndex(QComboBox *comboBox);
+ int currentComboFormatIndex(QComboBox* comboBox);
bool isOkToGo();
- bool runGpsbabel(const QStringList &args, QString &errorString, QString &outputString);
+ bool runGpsbabel(const QStringList& args, QString& errorString, QString& outputString);
void crossCheckInOutFormats();
- void setIndicatorLights(QLabel *label, const QString &type, int code) ;
- void displayOptionsText(QLineEdit *, QComboBox *, bool);
+ void setIndicatorLights(QLabel* label, const QString& type, int code) ;
+ void displayOptionsText(QLineEdit*, QComboBox*, bool);
void saveSettings();
void restoreSettings();
- void setComboToFormat(QComboBox *comboBox, const QString &, bool isFile);
- void setComboToDevice(QComboBox *comboBox, const QString &);
+ void setComboToFormat(QComboBox* comboBox, const QString&, bool isFile);
+ void setComboToDevice(QComboBox* comboBox, const QString&);
void loadDeviceNameCombos();
- void loadInputDeviceNameCombo(const QString &format);
- void loadOutputDeviceNameCombo(const QString &format);
- bool formatSupportsUSB(const QString &format);
- bool formatSupportsSerial(const QString &format);
+ void loadInputDeviceNameCombo(const QString& format);
+ void loadOutputDeviceNameCombo(const QString& format);
+ bool formatSupportsUSB(const QString& format);
+ bool formatSupportsSerial(const QString& format);
void loadCharSetCombos();
void checkCharSetCombos();
- QString charSetFromCombo(QComboBox *);
- void setComboToCharSet(QComboBox *, const QString &);
+ QString charSetFromCombo(QComboBox*);
+ void setComboToCharSet(QComboBox*, const QString&);
void updateFilterStatus();
void setWidgetValues();
void getWidgetValues();
- UpgradeCheck *upgrade;
+ UpgradeCheck* upgrade;
bool allowBetaUpgrades();
void osLoadDeviceNameCombos(QComboBox*);
QString getFormatNameForExtension(QString ext);
void closeEvent(QCloseEvent*);
void changeEvent(QEvent*);
- private slots:
+private slots:
void aboutActionX();
void applyActionX();
void browseInputFile();
void browseOutputFile();
void closeActionX();
void donateActionX();
- void dragEnterEvent(QDragEnterEvent *);
- void dropEvent(QDropEvent *event);
+ void dragEnterEvent(QDragEnterEvent*);
+ void dropEvent(QDropEvent* event);
void filtersClicked();
void helpActionX();
void inputDeviceOptBtnClicked();
using std::vector;
//------------------------------------------------------------------------
-static QString stripDoubleQuotes(const QString s) {
+static QString stripDoubleQuotes(const QString s)
+{
QString out;
foreach (QChar c, s) {
- if (c != QChar('"'))
+ if (c != QChar('"')) {
out += c;
+ }
}
return out;
}
//------------------------------------------------------------------------
-Map::Map(QWidget *parent,
- const Gpx &gpx, QPlainTextEdit *te):
+Map::Map(QWidget* parent,
+ const Gpx& gpx, QPlainTextEdit* te):
#if HAVE_WEBENGINE
- QWebEngineView(parent),
+ QWebEngineView(parent),
#else
- QWebView(parent),
+ QWebView(parent),
#endif
- gpx_(gpx),
- mapPresent_(false),
- busyCursor_(false),
- textEdit_(te)
+ gpx_(gpx),
+ mapPresent_(false),
+ busyCursor_(false),
+ textEdit_(te)
{
busyCursor_ = true;
stopWatch_.start();
QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
manager_ = new QNetworkAccessManager(this);
connect(this,SIGNAL(loadFinished(bool)),
- this,SLOT(loadFinishedX(bool)));
+ this,SLOT(loadFinishedX(bool)));
this->logTime("Start map constuctor");
#if HAVE_WEBENGINE
- MarkerClicker *mclicker = new MarkerClicker(this);
+ MarkerClicker* mclicker = new MarkerClicker(this);
QWebChannel* channel = new QWebChannel(this->page());
this->page()->setWebChannel(channel);
// Note: A current limitation is that objects must be registered before any client is initialized.
channel->registerObject(QStringLiteral("mclicker"), mclicker);
- connect(mclicker, SIGNAL(markerClicked(int, int )), this, SLOT(markerClicked(int, int)));
- connect(mclicker, SIGNAL(logTime(const QString &)), this, SLOT(logTime(const QString &)));
+ connect(mclicker, SIGNAL(markerClicked(int, int)), this, SLOT(markerClicked(int, int)));
+ connect(mclicker, SIGNAL(logTime(const QString&)), this, SLOT(logTime(const QString&)));
#endif
QString baseFile = QApplication::applicationDirPath() + "/gmapbase.html";
if (!QFile(baseFile).exists()) {
QMessageBox::critical(0, appName,
- tr("Missing \"gmapbase.html\" file. Check installation"));
- }
- else {
+ tr("Missing \"gmapbase.html\" file. Check installation"));
+ } else {
QString urlStr = "file:///" + baseFile;
this->load(QUrl(urlStr));
}
//------------------------------------------------------------------------
Map::~Map()
{
- if (busyCursor_)
+ if (busyCursor_) {
QApplication::restoreOverrideCursor();
+ }
#ifdef DEBUG_JS_GENERATION
if (dbgout_) {
delete dbgout_;
this->logTime("Done initial page load");
if (!f)
QMessageBox::critical(0, appName,
- tr("Failed to load Google maps base page"));
+ tr("Failed to load Google maps base page"));
else {
QApplication::processEvents();
showGpxData();
}
//------------------------------------------------------------------------
-static QString fmtLatLng(const LatLng &l) {
+static QString fmtLatLng(const LatLng& l)
+{
return QString("{lat: %1, lng: %3}").arg(l.lat(), 0, 'f', 5) .arg(l.lng(), 0, 'f', 5);
}
//------------------------------------------------------------------------
-static QString makePath(const vector <LatLng> &pts) {
- // maps v3 Polylines do not use encoded paths.
- QString path;
- int lncount = 0;
- bool someoutput = false;
- foreach (const LatLng ll, pts) {
- if (lncount == 0) {
- if (someoutput) {
- path.append(QChar(','));
- }
- path.append(QLatin1String("\n "));
- } else if (lncount == 1) {
- path.append(QLatin1String(", "));
+static QString makePath(const vector <LatLng>& pts)
+{
+ // maps v3 Polylines do not use encoded paths.
+ QString path;
+ int lncount = 0;
+ bool someoutput = false;
+ foreach (const LatLng ll, pts) {
+ if (lncount == 0) {
+ if (someoutput) {
+ path.append(QChar(','));
}
- path.append(fmtLatLng(ll));
- someoutput = true;
- lncount = (lncount + 1) % 2;
+ path.append(QLatin1String("\n "));
+ } else if (lncount == 1) {
+ path.append(QLatin1String(", "));
}
- return path;
+ path.append(fmtLatLng(ll));
+ someoutput = true;
+ lncount = (lncount + 1) % 2;
+ }
+ return path;
}
//------------------------------------------------------------------------
#if !defined(HAVE_WEBENGINE)
// Historically this was done here in showGpxData.
- MarkerClicker *mclicker = new MarkerClicker(this);
+ MarkerClicker* mclicker = new MarkerClicker(this);
this->page()->mainFrame()->addToJavaScriptWindowObject("mclicker", mclicker);
- connect(mclicker, SIGNAL(markerClicked(int, int )), this, SLOT(markerClicked(int, int)));
- connect(mclicker, SIGNAL(logTime(const QString &)), this, SLOT(logTime(const QString &)));
+ connect(mclicker, SIGNAL(markerClicked(int, int)), this, SLOT(markerClicked(int, int)));
+ connect(mclicker, SIGNAL(logTime(const QString&)), this, SLOT(logTime(const QString&)));
#endif
this->logTime("Start defining JS string");
QStringList scriptStr;
scriptStr
- << "mclicker.logTimeX(\"Start JS execution\");"
- << "var map = new google.maps.Map(document.getElementById(\"map\"));"
- << "var bounds = new google.maps.LatLngBounds();"
- << "var waypts = [];"
- << "var rtes = [];"
- << "var trks = [];"
- << "var idx;"
- << "mclicker.logTimeX(\"Done prelim JS definition\");"
- ;
+ << "mclicker.logTimeX(\"Start JS execution\");"
+ << "var map = new google.maps.Map(document.getElementById(\"map\"));"
+ << "var bounds = new google.maps.LatLngBounds();"
+ << "var waypts = [];"
+ << "var rtes = [];"
+ << "var trks = [];"
+ << "var idx;"
+ << "mclicker.logTimeX(\"Done prelim JS definition\");"
+ ;
mapPresent_ = true;
// Waypoints.
int num=0;
- foreach (const GpxWaypoint &pt, gpx_.getWaypoints() ) {
+ foreach (const GpxWaypoint& pt, gpx_.getWaypoints()) {
scriptStr
- << QString("waypts[%1] = new google.maps.Marker({map: map, position: %2, "
- "title: \"%3\", icon: blueIcon});")
- .arg(num)
- .arg(fmtLatLng(pt.getLocation()), stripDoubleQuotes(pt.getName()));
+ << QString("waypts[%1] = new google.maps.Marker({map: map, position: %2, "
+ "title: \"%3\", icon: blueIcon});")
+ .arg(num)
+ .arg(fmtLatLng(pt.getLocation()), stripDoubleQuotes(pt.getName()));
num++;
}
scriptStr
- << "for (idx = 0; idx < waypts.length; idx += 1) {"
- << " bounds.extend(waypts[idx].getPosition());"
- << " attachHandler(waypts[idx], new MarkerHandler(0, idx));"
- << "}"
- << "mclicker.logTimeX(\"Done waypoints definition\");"
- ;
+ << "for (idx = 0; idx < waypts.length; idx += 1) {"
+ << " bounds.extend(waypts[idx].getPosition());"
+ << " attachHandler(waypts[idx], new MarkerHandler(0, idx));"
+ << "}"
+ << "mclicker.logTimeX(\"Done waypoints definition\");"
+ ;
// Tracks
num = 0;
- foreach (const GpxTrack &trk, gpx_.getTracks()) {
+ foreach (const GpxTrack& trk, gpx_.getTracks()) {
vector <LatLng> pts;
QString path;
foreach (const GpxTrackSegment seg, trk.getTrackSegments()) {
path = makePath(pts);
scriptStr
- << QString("trks[%1] = new RTPolyline(\n"
- " map,\n"
- " new google.maps.Polyline({\n map: map,\n strokeColor: \"#0000E0\",\n strokeWeight: 2,\n strokeOpacity: 0.6,\n path: [%2\n ]\n }),\n"
- " new google.maps.LatLng(%3),\n"
- " new google.maps.LatLng(%4),\n"
- " \"%5\",\n"
- " new MarkerHandler(1, %1)\n);"
- ).arg(num).arg(path, fmtLatLng(pts.front()), fmtLatLng(pts.back()), stripDoubleQuotes(trk.getName()))
- << QString("bounds.union(trks[%1].getBounds());").arg(num)
- ;
+ << QString("trks[%1] = new RTPolyline(\n"
+ " map,\n"
+ " new google.maps.Polyline({\n map: map,\n strokeColor: \"#0000E0\",\n strokeWeight: 2,\n strokeOpacity: 0.6,\n path: [%2\n ]\n }),\n"
+ " new google.maps.LatLng(%3),\n"
+ " new google.maps.LatLng(%4),\n"
+ " \"%5\",\n"
+ " new MarkerHandler(1, %1)\n);"
+ ).arg(num).arg(path, fmtLatLng(pts.front()), fmtLatLng(pts.back()), stripDoubleQuotes(trk.getName()))
+ << QString("bounds.union(trks[%1].getBounds());").arg(num)
+ ;
num++;
}
scriptStr
- << "mclicker.logTimeX(\"Done track definition\");"
- ;
+ << "mclicker.logTimeX(\"Done track definition\");"
+ ;
// Routes
num = 0;
- foreach (const GpxRoute &rte, gpx_.getRoutes()) {
+ foreach (const GpxRoute& rte, gpx_.getRoutes()) {
vector <LatLng> pts;
QString path;
- foreach (const GpxRoutePoint &pt, rte.getRoutePoints()) {
+ foreach (const GpxRoutePoint& pt, rte.getRoutePoints()) {
pts.push_back(pt.getLocation());
}
path = makePath(pts);
scriptStr
- << QString("rtes[%1] = new RTPolyline(\n"
- " map,\n"
- " new google.maps.Polyline({\n map: map,\n strokeColor: \"#8000B0\",\n strokeWeight: 2,\n strokeOpacity: 0.6,\n path: [%2\n ]\n }),\n"
- " new google.maps.LatLng(%3),\n"
- " new google.maps.LatLng(%4),\n"
- " \"%5\",\n"
- " new MarkerHandler(2, %1)\n);"
- ).arg(num).arg(path, fmtLatLng(pts.front()), fmtLatLng(pts.back()), stripDoubleQuotes(rte.getName()))
- << QString("bounds.union(rtes[%1].getBounds());").arg(num)
- ;
+ << QString("rtes[%1] = new RTPolyline(\n"
+ " map,\n"
+ " new google.maps.Polyline({\n map: map,\n strokeColor: \"#8000B0\",\n strokeWeight: 2,\n strokeOpacity: 0.6,\n path: [%2\n ]\n }),\n"
+ " new google.maps.LatLng(%3),\n"
+ " new google.maps.LatLng(%4),\n"
+ " \"%5\",\n"
+ " new MarkerHandler(2, %1)\n);"
+ ).arg(num).arg(path, fmtLatLng(pts.front()), fmtLatLng(pts.back()), stripDoubleQuotes(rte.getName()))
+ << QString("bounds.union(rtes[%1].getBounds());").arg(num)
+ ;
num++;
}
scriptStr
- << "mclicker.logTimeX(\"Done route definition\");"
- ;
+ << "mclicker.logTimeX(\"Done route definition\");"
+ ;
scriptStr
- << "map.setCenter(bounds.getCenter());"
- << "map.fitBounds(bounds);"
- << "mclicker.logTimeX(\"Done setCenter\");"
- ;
+ << "map.setCenter(bounds.getCenter());"
+ << "map.fitBounds(bounds);"
+ << "mclicker.logTimeX(\"Done setCenter\");"
+ ;
this->logTime("Done defining JS string");
evaluateJS(scriptStr);
}
//------------------------------------------------------------------------
-void Map::markerClicked(int t, int i){
- if (t == 0)
+void Map::markerClicked(int t, int i)
+{
+ if (t == 0) {
emit waypointClicked(i);
- else if (t == 1)
+ } else if (t == 1) {
emit trackClicked(i);
- else if (t == 2)
+ } else if (t == 2) {
emit routeClicked(i);
+ }
}
//------------------------------------------------------------------------
-void Map::logTime(const QString &s)
+void Map::logTime(const QString& s)
{
// fprintf(stderr, "Log: %s: %d ms\n", s.toStdString().c_str(), stopWatch.elapsed());
if (textEdit_) {
stopWatch_.start();
}
//------------------------------------------------------------------------
-void Map::showTracks(const QList<GpxTrack> &tracks)
+void Map::showTracks(const QList<GpxTrack>& tracks)
{
QStringList scriptStr;
int i=0;
- foreach(const GpxTrack &trk, tracks) {
+ foreach (const GpxTrack& trk, tracks) {
scriptStr << QString("trks[%1].%2();").arg(i).arg(trk.getVisible()?"show":"hide");
i++;
}
{
QStringList scriptStr;
scriptStr
- << "for (idx = 0; idx < trks.length; idx += 1) {"
- << " trks[idx].hide();"
- << "}"
- ;
+ << "for (idx = 0; idx < trks.length; idx += 1) {"
+ << " trks[idx].hide();"
+ << "}"
+ ;
evaluateJS(scriptStr);
}
//------------------------------------------------------------------------
// TACKY: we assume the waypoints list and JS waypts[] are parallel.
-void Map::showWaypoints(const QList<GpxWaypoint> &waypoints)
+void Map::showWaypoints(const QList<GpxWaypoint>& waypoints)
{
QStringList scriptStr;
int i=0;
- foreach(const GpxWaypoint &pt, waypoints) {
+ foreach (const GpxWaypoint& pt, waypoints) {
scriptStr << QString("waypts[%1].setVisible(%2);").arg(i++).arg(pt.getVisible()?"true":"false");
}
evaluateJS(scriptStr);
{
QStringList scriptStr;
scriptStr
- << "for (idx = 0; idx < waypts.length; idx += 1) {"
- << " waypts[idx].setVisible(false);"
- << "}"
- ;
+ << "for (idx = 0; idx < waypts.length; idx += 1) {"
+ << " waypts[idx].setVisible(false);"
+ << "}"
+ ;
evaluateJS(scriptStr);
}
//------------------------------------------------------------------------
-void Map::showRoutes(const QList<GpxRoute> &routes)
+void Map::showRoutes(const QList<GpxRoute>& routes)
{
QStringList scriptStr;
int i=0;
- foreach(const GpxRoute &rt, routes) {
+ foreach (const GpxRoute& rt, routes) {
scriptStr << QString("rtes[%1].%2();").arg(i).arg(rt.getVisible()?"show":"hide");
i++;
}
{
QStringList scriptStr;
scriptStr
- << "for (idx = 0; idx < rtes.length; idx += 1) {"
- << " rtes[idx].hide();"
- << "}"
- ;
+ << "for (idx = 0; idx < rtes.length; idx += 1) {"
+ << " rtes[idx].hide();"
+ << "}"
+ ;
evaluateJS(scriptStr);
}
//------------------------------------------------------------------------
void Map::setWaypointVisibility(int i, bool show)
{
evaluateJS(QString("waypts[%1].setVisible(%2);\n")
- .arg(i).arg(show?"true": "false"));
+ .arg(i).arg(show?"true": "false"));
}
//------------------------------------------------------------------------
QString x = show?"show": "hide";
QStringList scriptStr;
scriptStr
- << QString("trks[%1].%2();").arg(i).arg(x)
- ;
+ << QString("trks[%1].%2();").arg(i).arg(x)
+ ;
evaluateJS(scriptStr);
}
QString x = show?"show": "hide";
QStringList scriptStr;
scriptStr
- << QString("rtes[%1].%2();").arg(i).arg(x)
- ;
+ << QString("rtes[%1].%2();").arg(i).arg(x)
+ ;
evaluateJS(scriptStr);
}
//------------------------------------------------------------------------
-void Map::panTo(const LatLng &loc)
+void Map::panTo(const LatLng& loc)
{
evaluateJS(QString("map.panTo(new google.maps.LatLng(%1));").arg(fmtLatLng(loc)));
}
//------------------------------------------------------------------------
-void Map::resizeEvent ( QResizeEvent * ev)
+void Map::resizeEvent(QResizeEvent* ev)
{
#if HAVE_WEBENGINE
QWebEngineView::resizeEvent(ev);
#else
QWebView::resizeEvent(ev);
#endif
- if (mapPresent_)
+ if (mapPresent_) {
evaluateJS(QString("map.checkResize();"));
+ }
}
//------------------------------------------------------------------------
QStringList scriptStr;
scriptStr
- << QString("map.setCenter(trks[%1].getBounds().getCenter());").arg(i)
- << QString("map.fitBounds(trks[%1].getBounds());").arg(i)
-
- ;
+ << QString("map.setCenter(trks[%1].getBounds().getCenter());").arg(i)
+ << QString("map.fitBounds(trks[%1].getBounds());").arg(i)
+
+ ;
evaluateJS(scriptStr);
}
{
QStringList scriptStr;
scriptStr
- << QString("map.setCenter(rtes[%1].getBounds().getCenter());").arg(i)
- << QString("map.fitBounds(rtes[%1].getBounds());").arg(i)
- ;
+ << QString("map.setCenter(rtes[%1].getBounds().getCenter());").arg(i)
+ << QString("map.fitBounds(rtes[%1].getBounds());").arg(i)
+ ;
evaluateJS(scriptStr);
}
//------------------------------------------------------------------------
-void Map::evaluateJS(const QString &s, bool upd)
+void Map::evaluateJS(const QString& s, bool upd)
{
#ifdef DEBUG_JS_GENERATION
*dbgout_ << s;
}
//------------------------------------------------------------------------
-void Map::evaluateJS(const QStringList &s, bool upd)
+void Map::evaluateJS(const QStringList& s, bool upd)
{
evaluateJS(s.join("\n"), upd);
}
class QNetworkAccessManager;
-class MarkerClicker: public QObject {
-Q_OBJECT
+class MarkerClicker: public QObject
+{
+ Q_OBJECT
public:
- MarkerClicker(QObject *parent): QObject(parent) {};
+ MarkerClicker(QObject* parent): QObject(parent) {};
public slots:
- void clickedX(int t, int i) {
+ void clickedX(int t, int i)
+ {
emit markerClicked(t, i);
}
- void logTimeX(const QString &s) {
+ void logTimeX(const QString& s)
+ {
emit logTime(s);
}
signals:
void markerClicked(int t, int i);
- void logTime(const QString &s);
+ void logTime(const QString& s);
};
#endif
{
Q_OBJECT
- public:
- Map(QWidget *parent,
- const Gpx &gpx_, QPlainTextEdit *textEdit_);
+public:
+ Map(QWidget* parent,
+ const Gpx& gpx_, QPlainTextEdit* textEdit_);
~Map();
- public slots:
+public slots:
void showGpxData();
- void showTracks(const QList<GpxTrack> &tracks);
+ void showTracks(const QList<GpxTrack>& tracks);
void hideAllTracks();
void setTrackVisibility(int i, bool show);
- void showWaypoints(const QList<GpxWaypoint> &waypoints);
+ void showWaypoints(const QList<GpxWaypoint>& waypoints);
void hideAllWaypoints();
void setWaypointVisibility(int i, bool show);
- void showRoutes(const QList<GpxRoute> &routes);
+ void showRoutes(const QList<GpxRoute>& routes);
void hideAllRoutes();
void setRouteVisibility(int i, bool show);
void loadFinishedX(bool);
void markerClicked(int t, int i);
- void panTo(const LatLng &loc);
+ void panTo(const LatLng& loc);
void setWaypointColorRed(int i);
void setWaypointColorBlue(int i);
void frameTrack(int i);
void frameRoute(int i);
- void logTime(const QString &);
-
- signals:
+ void logTime(const QString&);
+
+signals:
void waypointClicked(int i);
void trackClicked(int i);
void routeClicked(int i);
-
- private:
+
+private:
#ifdef DEBUG_JS_GENERATION
- QFile *dbgdata_;
- QTextStream *dbgout_;
+ QFile* dbgdata_;
+ QTextStream* dbgout_;
#endif
- QNetworkAccessManager *manager_;
- const Gpx &gpx_;
+ QNetworkAccessManager* manager_;
+ const Gpx& gpx_;
bool mapPresent_;
bool busyCursor_;
QTime stopWatch_;
- QPlainTextEdit *textEdit_;
+ QPlainTextEdit* textEdit_;
+
+ void evaluateJS(const QString& s, bool update = true);
+ void evaluateJS(const QStringList& s, bool update = true);
- void evaluateJS(const QString &s, bool update = true);
- void evaluateJS(const QStringList &s, bool update = true);
-
protected:
- virtual void resizeEvent ( QResizeEvent * event );
-
+ virtual void resizeEvent(QResizeEvent* event);
+
};
#include "format.h"
-class FileDlgManager: public QObject
+class FileDlgManager: public QObject
{
-Q_OBJECT
+ Q_OBJECT
public:
- FileDlgManager(QObject*parent,
- QLineEdit *le,
- QToolButton *tb, bool isInFile);
-
+ FileDlgManager(QObject* parent,
+ QLineEdit* le,
+ QToolButton* tb, bool isInFile);
+
~FileDlgManager();
private:
- QLineEdit *le;
- QToolButton *tb;
+ QLineEdit* le;
+ QToolButton* tb;
bool isInFile;
-
+
private slots:
void buttonClicked();
};
-class OptionsDlg: public QDialog {
-Q_OBJECT
- public:
- OptionsDlg(QWidget *parent, const QString &fmtName_, QList<FormatOption> *options_,
- const QString &html_);
-
- private:
+class OptionsDlg: public QDialog
+{
+ Q_OBJECT
+public:
+ OptionsDlg(QWidget* parent, const QString& fmtName_, QList<FormatOption>* options_,
+ const QString& html_);
+
+private:
QString fmtName_;
- QList<FormatOption> &options_;
- QDialogButtonBox *buttonBox_;
+ QList<FormatOption>& options_;
+ QDialogButtonBox* buttonBox_;
QList<QCheckBox*> checkBoxes_;
QList<QWidget*> fields_;
QString html_;
- private slots:
+private slots:
void acceptClicked();
void rejectClicked();
void helpClicked();
-
+
};
#include "preferences.h"
#include "../gbversion.h"
-class FormatListEntry : public QListWidgetItem {
- public:
- FormatListEntry(Format& fmt) /*: fmt_(fmt)*/ {
+class FormatListEntry : public QListWidgetItem
+{
+public:
+ FormatListEntry(Format& fmt) /*: fmt_(fmt)*/
+ {
setText(fmt.getDescription());
bool enabled = !fmt.isHidden();
setCheckState(enabled ? Qt::Checked : Qt::Unchecked);
}
- private:
- //Format& fmt_;
+private:
+ //Format& fmt_;
};
Preferences::Preferences(QWidget* parent, QList<Format>& formatList,
ui_.reportStatisticsCheck->setChecked(babelData_.reportStatistics_);
ui_.ignoreVersionMismatchCheck->setChecked(babelData_.ignoreVersionMismatch_);
// Because of an unfortunate bug in 1.4.0, we turn this off in 1.4.1.
- if (VERSION == QString("1.4.1"))
+ if (VERSION == QString("1.4.1")) {
babelData_.ignoreVersionMismatch_ = false;
+ }
- connect (ui_.buttonBox, SIGNAL(accepted()), this, SLOT(acceptClicked()));
- connect (ui_.buttonBox, SIGNAL(rejected()), this, SLOT(rejectClicked()));
+ connect(ui_.buttonBox, SIGNAL(accepted()), this, SLOT(acceptClicked()));
+ connect(ui_.buttonBox, SIGNAL(rejected()), this, SLOT(rejectClicked()));
- connect (ui_.enableAllButton, SIGNAL(clicked()), this, SLOT(enableAllClicked()));
- connect (ui_.disableAllButton, SIGNAL(clicked()), this, SLOT(disableAllClicked()));
+ connect(ui_.enableAllButton, SIGNAL(clicked()), this, SLOT(enableAllClicked()));
+ connect(ui_.disableAllButton, SIGNAL(clicked()), this, SLOT(disableAllClicked()));
for (int i = 0; i < formatList_.size(); i++) {
- FormatListEntry *item = new FormatListEntry(formatList[i]);
+ FormatListEntry* item = new FormatListEntry(formatList[i]);
ui_.enabledFormatsList->addItem(item);
}
#include "babeldata.h"
#include "format.h"
-class Preferences : public QDialog {
+class Preferences : public QDialog
+{
Q_OBJECT
- public:
+public:
Preferences(QWidget* parent, QList<Format>& formatList, BabelData& bd);
- private:
+private:
QList<Format>& formatList_;
Ui_Preferences ui_;
BabelData& babelData_;
- private slots:
+private slots:
void enableAllClicked();
void disableAllClicked();
void acceptClicked();
//------------------------------------------------------------------------
-QString ProcessWaitDialog::processErrorString( QProcess::ProcessError err)
+QString ProcessWaitDialog::processErrorString(QProcess::ProcessError err)
{
- switch (err)
- {
- case QProcess::FailedToStart:
- return QString(tr("Process failed to start"));
- break;
- case QProcess::Crashed:
- return QString(tr("Process crashed"));
- break;
- case QProcess::Timedout:
- return QString(tr("Process timedout"));
- break;
- case QProcess::WriteError:
- return QString(tr("Error while trying to write to process"));
- break;
- case QProcess::ReadError:
- return QString(tr("Error while trying to read from process"));
- break;
- case QProcess::UnknownError:
- default:
- return QString(tr("Unknown process error"));
- }
+ switch (err) {
+ case QProcess::FailedToStart:
+ return QString(tr("Process failed to start"));
+ break;
+ case QProcess::Crashed:
+ return QString(tr("Process crashed"));
+ break;
+ case QProcess::Timedout:
+ return QString(tr("Process timedout"));
+ break;
+ case QProcess::WriteError:
+ return QString(tr("Error while trying to write to process"));
+ break;
+ case QProcess::ReadError:
+ return QString(tr("Error while trying to read from process"));
+ break;
+ case QProcess::UnknownError:
+ default:
+ return QString(tr("Unknown process error"));
+ }
return QString("");
}
//------------------------------------------------------------------------
-ProcessWaitDialog::ProcessWaitDialog(QWidget *parent, QProcess *process):
+ProcessWaitDialog::ProcessWaitDialog(QWidget* parent, QProcess* process):
QDialog(parent), process_(process)
{
this->resize(400, 220);
this->setWindowTitle(QString(appName) + tr(" ... Process GPSBabel"));
- QVBoxLayout *layout = new QVBoxLayout(this);
+ QVBoxLayout* layout = new QVBoxLayout(this);
textEdit_ = new QPlainTextEdit(this);
textEdit_->setReadOnly(true);
layout->addWidget(buttonBox_);
connect(process, SIGNAL(error(QProcess::ProcessError)),
- this, SLOT (errorX(QProcess::ProcessError)));
+ this, SLOT(errorX(QProcess::ProcessError)));
connect(process, SIGNAL(finished(int, QProcess::ExitStatus)),
- this, SLOT (finishedX(int, QProcess::ExitStatus)));
+ this, SLOT(finishedX(int, QProcess::ExitStatus)));
connect(process, SIGNAL(readyReadStandardError()),
- this, SLOT (readyReadStandardErrorX()));
+ this, SLOT(readyReadStandardErrorX()));
connect(process, SIGNAL(readyReadStandardOutput()),
- this, SLOT (readyReadStandardOutputX()));
+ this, SLOT(readyReadStandardOutputX()));
connect(btn, SIGNAL(clicked()),
- this, SLOT (stopClickedX()));
+ this, SLOT(stopClickedX()));
exitStatus_ = QProcess::CrashExit; // Assume all errors are crashes for now.
bufferedOut_ = "";
//
- for (int i=0; i<=100; i+=2)
+ for (int i=0; i<=100; i+=2) {
progressVals_.push_back(i);
- for (int i=98; i>0; i-=2)
+ }
+ for (int i=98; i>0; i-=2) {
progressVals_.push_back(i);
+ }
progressIndex_ = progressVals_.size()/2;
timer_ = new QTimer(this);
progressIndex_++;
int idx = progressIndex_ % progressVals_.size();
progressBar_->setValue(progressVals_[idx]);
- if (stopCount_ >=0)
+ if (stopCount_ >=0) {
stopCount_++;
+ }
if (stopCount_ > 150) {
process_->kill();
errorString_ = QString(tr("Process did not terminate successfully"));
void ProcessWaitDialog::finishedX(int exitCode, QProcess::ExitStatus es)
{
ecode_ = exitCode;
- if (es == QProcess::CrashExit)
+ if (es == QProcess::CrashExit) {
errorString_ = QString(tr("Process crashed whle running"));
+ }
timer_->stop();
accept();
};
// appendPlainText automatically puts in a new line with every call. That's
// why you have to buffer it, and only append when we get a real newline.
//
-void ProcessWaitDialog::appendToText(const char *ptr)
+void ProcessWaitDialog::appendToText(const char* ptr)
{
outputString_ += QString(ptr);
- for (const char *cptr = ptr; *cptr; cptr++) {
- if (*cptr == '\r')
+ for (const char* cptr = ptr; *cptr; cptr++) {
+ if (*cptr == '\r') {
continue;
+ }
if (*cptr == '\n') {
textEdit_->appendPlainText(QString::fromStdString(bufferedOut_));
bufferedOut_ = "";
//------------------------------------------------------------------------
void ProcessWaitDialog::readyReadStandardOutputX()
- {
+{
QByteArray d = process_->readAllStandardOutput();
appendToText(d.data());
};
-void ProcessWaitDialog::closeEvent(QCloseEvent *event)
+void ProcessWaitDialog::closeEvent(QCloseEvent* event)
{
- event->ignore();
+ event->ignore();
};
class QDialogButtonBox;
class QTimer;
//------------------------------------------------------------------------
-class ProcessWaitDialog: public QDialog
+class ProcessWaitDialog: public QDialog
{
-
+
Q_OBJECT
-
- public:
+
+public:
//
- ProcessWaitDialog(QWidget *parent, QProcess *process_);
+ ProcessWaitDialog(QWidget* parent, QProcess* process_);
~ProcessWaitDialog();
-
+
bool getExitedNormally();
int getExitCode();
QString getErrorString();
- QString getOutputString() const {return outputString_;};
+ QString getOutputString() const
+ {
+ return outputString_;
+ };
- protected:
- void closeEvent (QCloseEvent*event);
- void appendToText(const char *);
+protected:
+ void closeEvent(QCloseEvent* event);
+ void appendToText(const char*);
QString processErrorString(QProcess::ProcessError err);
-
- private slots:
+
+private slots:
void errorX(QProcess::ProcessError);
void finishedX(int exitCode, QProcess::ExitStatus);
void readyReadStandardErrorX();
void timeoutX();
void stopClickedX();
- private:
+private:
vector <int> progressVals_;
int progressIndex_;
int stopCount_;
string bufferedOut_;
QProcess::ExitStatus exitStatus_;
int ecode_;
- QProcess *process_;
- QProgressBar *progressBar_;
- QPlainTextEdit *textEdit_;
- QDialogButtonBox *buttonBox_;
- QTimer *timer_;
+ QProcess* process_;
+ QProgressBar* progressBar_;
+ QPlainTextEdit* textEdit_;
+ QDialogButtonBox* buttonBox_;
+ QTimer* timer_;
QString errorString_;
QString outputString_;
};
// Apple's copyright blob:
/*
Copyright: © Copyright 2000-2005 Apple Computer, Inc. All rights reserved.
-
+
Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc.
("Apple") in consideration of your agreement to the following terms, and your
use, installation, modification or redistribution of this Apple software
OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT
(INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
+
*/
#include <stdio.h>
#include "mainwindow.h"
// Function prototypes
-static kern_return_t FindModems(io_iterator_t *matchingServices);
+static kern_return_t FindModems(io_iterator_t* matchingServices);
// static kern_return_t GetModemPath(io_iterator_t serialPortIterator, char *bsdPath, CFIndex maxPathSize);
// static int OpenSerialPort(const char *bsdPath);
// Returns an iterator across all known modems. Caller is responsible for
// releasing the iterator when iteration is complete.
-static kern_return_t FindModems(io_iterator_t *matchingServices)
+static kern_return_t FindModems(io_iterator_t* matchingServices)
{
- kern_return_t kernResult;
- CFMutableDictionaryRef classesToMatch;
-
-/*! @function IOServiceMatching
- @abstract Create a matching dictionary that specifies an IOService class match.
- @discussion A very common matching criteria for IOService is based on its class. IOServiceMatching will create a matching dictionary that specifies any IOService of a class, or its subclasses. The class is specified by C-string name.
- @param name The class name, as a const C-string. Class matching is successful on IOService's of this class or any subclass.
- @result The matching dictionary created, is returned on success, or zero on failure. The dictionary is commonly passed to IOServiceGetMatchingServices or IOServiceAddNotification which will consume a reference, otherwise it should be released with CFRelease by the caller. */
-
- // Serial devices are instances of class IOSerialBSDClient
- classesToMatch = IOServiceMatching(kIOSerialBSDServiceValue);
- if (classesToMatch == NULL)
- {
- printf("IOServiceMatching returned a NULL dictionary.\n");
- }
- else {
-/*!
- @function CFDictionarySetValue
- Sets the value of the key in the dictionary.
- @param theDict The dictionary to which the value is to be set. If this
- parameter is not a valid mutable CFDictionary, the behavior is
- undefined. If the dictionary is a fixed-capacity dictionary and
- it is full before this operation, and the key does not exist in
- the dictionary, the behavior is undefined.
- @param key The key of the value to set into the dictionary. If a key
- which matches this key is already present in the dictionary, only
- the value is changed ("add if absent, replace if present"). If
- no key matches the given key, the key-value pair is added to the
- dictionary. If added, the key is retained by the dictionary,
- using the retain callback provided
- when the dictionary was created. If the key is not of the sort
- expected by the key retain callback, the behavior is undefined.
- @param value The value to add to or replace into the dictionary. The value
- is retained by the dictionary using the retain callback provided
- when the dictionary was created, and the previous value if any is
- released. If the value is not of the sort expected by the
- retain or release callbacks, the behavior is undefined.
-*/
+ kern_return_t kernResult;
+ CFMutableDictionaryRef classesToMatch;
+
+ /*! @function IOServiceMatching
+ @abstract Create a matching dictionary that specifies an IOService class match.
+ @discussion A very common matching criteria for IOService is based on its class. IOServiceMatching will create a matching dictionary that specifies any IOService of a class, or its subclasses. The class is specified by C-string name.
+ @param name The class name, as a const C-string. Class matching is successful on IOService's of this class or any subclass.
+ @result The matching dictionary created, is returned on success, or zero on failure. The dictionary is commonly passed to IOServiceGetMatchingServices or IOServiceAddNotification which will consume a reference, otherwise it should be released with CFRelease by the caller. */
+
+ // Serial devices are instances of class IOSerialBSDClient
+ classesToMatch = IOServiceMatching(kIOSerialBSDServiceValue);
+ if (classesToMatch == NULL) {
+ printf("IOServiceMatching returned a NULL dictionary.\n");
+ } else {
+ /*!
+ @function CFDictionarySetValue
+ Sets the value of the key in the dictionary.
+ @param theDict The dictionary to which the value is to be set. If this
+ parameter is not a valid mutable CFDictionary, the behavior is
+ undefined. If the dictionary is a fixed-capacity dictionary and
+ it is full before this operation, and the key does not exist in
+ the dictionary, the behavior is undefined.
+ @param key The key of the value to set into the dictionary. If a key
+ which matches this key is already present in the dictionary, only
+ the value is changed ("add if absent, replace if present"). If
+ no key matches the given key, the key-value pair is added to the
+ dictionary. If added, the key is retained by the dictionary,
+ using the retain callback provided
+ when the dictionary was created. If the key is not of the sort
+ expected by the key retain callback, the behavior is undefined.
+ @param value The value to add to or replace into the dictionary. The value
+ is retained by the dictionary using the retain callback provided
+ when the dictionary was created, and the previous value if any is
+ released. If the value is not of the sort expected by the
+ retain or release callbacks, the behavior is undefined.
+ */
// CFDictionarySetValue(classesToMatch,
// CFSTR(kIOSerialBSDTypeKey),
// CFSTR(kIOSerialBSDModemType));
- // Each serial device object has a property with key
- // kIOSerialBSDTypeKey and a value that is one of kIOSerialBSDAllTypes,
- // kIOSerialBSDModemType, or kIOSerialBSDRS232Type. You can experiment with the
- // matching by changing the last parameter in the above call to CFDictionarySetValue.
-
- // As shipped, this sample is only interested in modems,
- // so add this property to the CFDictionary we're matching on.
- // This will find devices that advertise themselves as modems,
- // such as built-in and USB modems. However, this match won't find serial modems.
- }
-
- /*! @function IOServiceGetMatchingServices
- @abstract Look up registered IOService objects that match a matching dictionary.
- @discussion This is the preferred method of finding IOService objects currently registered by IOKit. IOServiceAddNotification can also supply this information and install a notification of new IOServices. The matching information used in the matching dictionary may vary depending on the class of service being looked up.
- @param masterPort The master port obtained from IOMasterPort().
- @param matching A CF dictionary containing matching information, of which one reference is consumed by this function. IOKitLib can contruct matching dictionaries for common criteria with helper functions such as IOServiceMatching, IOOpenFirmwarePathMatching.
- @param existing An iterator handle is returned on success, and should be released by the caller when the iteration is finished.
- @result A kern_return_t error code. */
-
- kernResult = IOServiceGetMatchingServices(kIOMasterPortDefault, classesToMatch, matchingServices);
- if (KERN_SUCCESS != kernResult)
- {
- printf("IOServiceGetMatchingServices returned %d\n", kernResult);
- goto exit;
- }
+ // Each serial device object has a property with key
+ // kIOSerialBSDTypeKey and a value that is one of kIOSerialBSDAllTypes,
+ // kIOSerialBSDModemType, or kIOSerialBSDRS232Type. You can experiment with the
+ // matching by changing the last parameter in the above call to CFDictionarySetValue.
+
+ // As shipped, this sample is only interested in modems,
+ // so add this property to the CFDictionary we're matching on.
+ // This will find devices that advertise themselves as modems,
+ // such as built-in and USB modems. However, this match won't find serial modems.
+ }
+
+ /*! @function IOServiceGetMatchingServices
+ @abstract Look up registered IOService objects that match a matching dictionary.
+ @discussion This is the preferred method of finding IOService objects currently registered by IOKit. IOServiceAddNotification can also supply this information and install a notification of new IOServices. The matching information used in the matching dictionary may vary depending on the class of service being looked up.
+ @param masterPort The master port obtained from IOMasterPort().
+ @param matching A CF dictionary containing matching information, of which one reference is consumed by this function. IOKitLib can contruct matching dictionaries for common criteria with helper functions such as IOServiceMatching, IOOpenFirmwarePathMatching.
+ @param existing An iterator handle is returned on success, and should be released by the caller when the iteration is finished.
+ @result A kern_return_t error code. */
+
+ kernResult = IOServiceGetMatchingServices(kIOMasterPortDefault, classesToMatch, matchingServices);
+ if (KERN_SUCCESS != kernResult) {
+ printf("IOServiceGetMatchingServices returned %d\n", kernResult);
+ goto exit;
+ }
exit:
- return kernResult;
+ return kernResult;
}
// Given an iterator across a set of modems, return the BSD path to the first one.
// If no modems are found the path name is set to an empty string.
-static kern_return_t GetModemPath(io_iterator_t serialPortIterator, char *bsdPath, CFIndex maxPathSize, QComboBox *box)
+static kern_return_t GetModemPath(io_iterator_t serialPortIterator, char* bsdPath, CFIndex maxPathSize, QComboBox* box)
{
- io_object_t modemService;
- kern_return_t kernResult = KERN_FAILURE;
- Boolean modemFound = false;
-
- // Initialize the returned path
- *bsdPath = '\0';
-
- // Iterate across all modems found. In this example, we bail after finding the first modem.
-
- while ((modemService = IOIteratorNext(serialPortIterator)) && !modemFound)
- {
- CFTypeRef bsdPathAsCFString;
-
- // Get the callout device's path (/dev/cu.xxxxx). The callout device should almost always be
- // used: the dialin device (/dev/tty.xxxxx) would be used when monitoring a serial port for
- // incoming calls, e.g. a fax listener.
-
- bsdPathAsCFString = IORegistryEntryCreateCFProperty(modemService,
- CFSTR(kIOCalloutDeviceKey),
- kCFAllocatorDefault,
- 0);
- if (bsdPathAsCFString)
- {
- Boolean result;
-
- // Convert the path from a CFString to a C (NUL-terminated) string for use
- // with the POSIX open() call.
-
- result = CFStringGetCString((const __CFString*) bsdPathAsCFString,
- bsdPath,
- maxPathSize,
- kCFStringEncodingUTF8);
- CFRelease(bsdPathAsCFString);
-
- if (result) {
- box->addItem(bsdPath);
- }
- }
-
- // Release the io_service_t now that we are done with it.
-
-// (void) IOObjectRelease(modemService);
+ io_object_t modemService;
+ kern_return_t kernResult = KERN_FAILURE;
+ Boolean modemFound = false;
+
+ // Initialize the returned path
+ *bsdPath = '\0';
+
+ // Iterate across all modems found. In this example, we bail after finding the first modem.
+
+ while ((modemService = IOIteratorNext(serialPortIterator)) && !modemFound) {
+ CFTypeRef bsdPathAsCFString;
+
+ // Get the callout device's path (/dev/cu.xxxxx). The callout device should almost always be
+ // used: the dialin device (/dev/tty.xxxxx) would be used when monitoring a serial port for
+ // incoming calls, e.g. a fax listener.
+
+ bsdPathAsCFString = IORegistryEntryCreateCFProperty(modemService,
+ CFSTR(kIOCalloutDeviceKey),
+ kCFAllocatorDefault,
+ 0);
+ if (bsdPathAsCFString) {
+ Boolean result;
+
+ // Convert the path from a CFString to a C (NUL-terminated) string for use
+ // with the POSIX open() call.
+
+ result = CFStringGetCString((const __CFString*) bsdPathAsCFString,
+ bsdPath,
+ maxPathSize,
+ kCFStringEncodingUTF8);
+ CFRelease(bsdPathAsCFString);
+
+ if (result) {
+ box->addItem(bsdPath);
+ }
}
- return kernResult;
+ // Release the io_service_t now that we are done with it.
+
+// (void) IOObjectRelease(modemService);
+ }
+
+ return kernResult;
}
#include "mainwindow.h"
-void MainWindow::osLoadDeviceNameCombos(QComboBox *box)
+void MainWindow::osLoadDeviceNameCombos(QComboBox* box)
{
kern_return_t kernResult;
io_iterator_t serialPortIterator;
static QStringList dynamicDevices()
{
- struct udev *udev = udev_new();
- if(!udev) {
- qDebug() << "Can't create udev";
- return QStringList();
- }
+ struct udev* udev = udev_new();
+ if (!udev) {
+ qDebug() << "Can't create udev";
+ return QStringList();
+ }
- QSet<QString> devices;
+ QSet<QString> devices;
- struct udev_enumerate *enumerate = udev_enumerate_new(udev);
- udev_enumerate_add_match_subsystem(enumerate, "tty");
- udev_enumerate_scan_devices(enumerate);
+ struct udev_enumerate* enumerate = udev_enumerate_new(udev);
+ udev_enumerate_add_match_subsystem(enumerate, "tty");
+ udev_enumerate_scan_devices(enumerate);
- struct udev_list_entry *device;
- udev_list_entry_foreach(device, udev_enumerate_get_list_entry(enumerate)) {
- const char *path = udev_list_entry_get_name(device);
- struct udev_device *dev = udev_device_new_from_syspath(udev, path);
+ struct udev_list_entry* device;
+ udev_list_entry_foreach(device, udev_enumerate_get_list_entry(enumerate)) {
+ const char* path = udev_list_entry_get_name(device);
+ struct udev_device* dev = udev_device_new_from_syspath(udev, path);
- bool okMaj, okMin;
- int major = QString(udev_device_get_property_value(dev, "MAJOR")).toInt(&okMaj);
- int minor = QString(udev_device_get_property_value(dev, "MINOR")).toInt(&okMin);
- if(!okMaj || !okMin) {
- major = -1;
- minor = -1;
- }
+ bool okMaj, okMin;
+ int major = QString(udev_device_get_property_value(dev, "MAJOR")).toInt(&okMaj);
+ int minor = QString(udev_device_get_property_value(dev, "MINOR")).toInt(&okMin);
+ if (!okMaj || !okMin) {
+ major = -1;
+ minor = -1;
+ }
- // see Documentation/devices.txt in the linux tree
- if( !( (major == 4 || major == 5) && 0 <= minor && minor <= 63 ) ) {
- devices << QString::fromUtf8(udev_device_get_devnode(dev));
- /*
- udev_device_get_sysattr_list_entry(dev);
- udev_device_get_tags_list_entry(dev);
- struct udev_list_entry *prop;
- qDebug() << "Device Node Path:" << udev_device_get_devnode(dev) << path;
- udev_list_entry_foreach(prop, udev_device_get_properties_list_entry(dev)) {
- qDebug() << " " << udev_list_entry_get_name(prop)
- << "=>" << udev_list_entry_get_value(prop);
- }
- */
- }
- udev_device_unref(dev);
+ // see Documentation/devices.txt in the linux tree
+ if (!((major == 4 || major == 5) && 0 <= minor && minor <= 63)) {
+ devices << QString::fromUtf8(udev_device_get_devnode(dev));
+ /*
+ udev_device_get_sysattr_list_entry(dev);
+ udev_device_get_tags_list_entry(dev);
+ struct udev_list_entry *prop;
+ qDebug() << "Device Node Path:" << udev_device_get_devnode(dev) << path;
+ udev_list_entry_foreach(prop, udev_device_get_properties_list_entry(dev)) {
+ qDebug() << " " << udev_list_entry_get_name(prop)
+ << "=>" << udev_list_entry_get_value(prop);
+ }
+ */
}
- udev_enumerate_unref(enumerate);
- udev_unref(udev);
+ udev_device_unref(dev);
+ }
+ udev_enumerate_unref(enumerate);
+ udev_unref(udev);
- QStringList list = devices.toList();
- qSort(list);
- return list;
+ QStringList list = devices.toList();
+ qSort(list);
+ return list;
}
#else
static QStringList dynamicDevices()
{
- return QStringList();
+ return QStringList();
}
#endif
-static const char *deviceNames[] = {
+static const char* deviceNames[] = {
"/dev/ttyS0",
"/dev/ttyS1",
"/dev/ttyS2",
0
};
-void MainWindow::osLoadDeviceNameCombos(QComboBox *box)
+void MainWindow::osLoadDeviceNameCombos(QComboBox* box)
{
const QStringList devices = dynamicDevices();
box->addItems(devices);
for (int i=0; deviceNames[i]; i++) {
- if(!devices.contains(deviceNames[i])) {
+ if (!devices.contains(deviceNames[i])) {
box->addItem(deviceNames[i]);
}
}
#if 0 // Does not require Windows 2000
-static const char *deviceNames[] = {
+static const char* deviceNames[] = {
"com1:",
"com2:",
"com3:",
0
};
-void MainWindow::osLoadDeviceNameCombos(QComboBox *box)
+void MainWindow::osLoadDeviceNameCombos(QComboBox* box)
{
for (int i=0; deviceNames[i]; i++) {
box->addItem(deviceNames[i]);
#else // This code assumes Windows 2000 or later
// Uses QueryDosDevice(), Minimum supported: Windows 2000 Professional/Server
-#include <windows.h>
+#include <windows.h>
#include <stdio.h>
-void MainWindow::osLoadDeviceNameCombos(QComboBox *box)
+void MainWindow::osLoadDeviceNameCombos(QComboBox* box)
{
char DevList[64*1024-1]; // a single byte more, and certain versions of windows
- // always return QueryDosDevice()==0 && GetLastError()==ERROR_MORE_DATA.
- // see http://support.microsoft.com/kb/931305
+ // always return QueryDosDevice()==0 && GetLastError()==ERROR_MORE_DATA.
+ // see http://support.microsoft.com/kb/931305
// Get a list of all existing MS-DOS device names. Stores one or more asciiz strings followed by an extra null.
DWORD res = QueryDosDeviceA(NULL, DevList, sizeof(DevList));
- if (res == 0)
- {
+ if (res == 0) {
DWORD err = GetLastError(); // could check for ERROR_INSUFFICIENT_BUFFER, and retry with a larger buffer.
- // but DevList is already at the maximum size it can be without running into kb 931305.
+ // but DevList is already at the maximum size it can be without running into kb 931305.
// FIXME: This shold be a QMessageBox::warning() - RJL
// fprintf(stderr,"QueryDosDevice() failed with %d. GetLastError()==%d.\n", res, err);
(void) err;
return;
}
- for (char *p=DevList; *p;) {
+ for (char* p=DevList; *p;) {
int len = strlen(p);
- if (strncmp(p,"COM",3)==0)
+ if (strncmp(p,"COM",3)==0) {
box->addItem((PCHAR)p);
+ }
p += len+1; // +1 to also skip the null character of each string
}
}
//------------------------------------------------------------------------
-class VarSetting {
- public:
+class VarSetting
+{
+public:
VarSetting() {};
virtual ~VarSetting() {};
- virtual void saveSetting(QSettings &) = 0;
- virtual void restoreSetting(QSettings &) = 0;
+ virtual void saveSetting(QSettings&) = 0;
+ virtual void restoreSetting(QSettings&) = 0;
};
//------------------------------------------------------------------------
class IntSetting: public VarSetting
{
- public:
- IntSetting(const QString &name, int &var): VarSetting(), name_(name), var_(var) { }
- void saveSetting(QSettings &st) {st.setValue(name_, var_); }
- void restoreSetting(QSettings &st) {if (st.contains(name_)) var_ = st.value(name_).toInt(); }
+public:
+ IntSetting(const QString& name, int& var): VarSetting(), name_(name), var_(var) { }
+ void saveSetting(QSettings& st)
+ {
+ st.setValue(name_, var_);
+ }
+ void restoreSetting(QSettings& st)
+ {
+ if (st.contains(name_)) {
+ var_ = st.value(name_).toInt();
+ }
+ }
- private:
+private:
QString name_;
- int &var_;
+ int& var_;
};
//------------------------------------------------------------------------
class DoubleSetting: public VarSetting
{
- public:
- DoubleSetting(const QString &name, double &var): VarSetting(), name_(name), var_(var) { }
- void saveSetting(QSettings &st) {st.setValue(name_, var_); }
- void restoreSetting(QSettings &st) {if (st.contains(name_)) var_ = st.value(name_).toDouble(); }
+public:
+ DoubleSetting(const QString& name, double& var): VarSetting(), name_(name), var_(var) { }
+ void saveSetting(QSettings& st)
+ {
+ st.setValue(name_, var_);
+ }
+ void restoreSetting(QSettings& st)
+ {
+ if (st.contains(name_)) {
+ var_ = st.value(name_).toDouble();
+ }
+ }
- private:
+private:
QString name_;
- double &var_;
+ double& var_;
};
//------------------------------------------------------------------------
class StringSetting: public VarSetting
{
- public:
- StringSetting(const QString &name, QString &var): VarSetting(), name_(name), var_(var) { }
- void saveSetting(QSettings &st) {st.setValue(name_, var_); }
- void restoreSetting(QSettings &st) {if (st.contains(name_)) var_ = st.value(name_).toString(); }
+public:
+ StringSetting(const QString& name, QString& var): VarSetting(), name_(name), var_(var) { }
+ void saveSetting(QSettings& st)
+ {
+ st.setValue(name_, var_);
+ }
+ void restoreSetting(QSettings& st)
+ {
+ if (st.contains(name_)) {
+ var_ = st.value(name_).toString();
+ }
+ }
- private:
+private:
QString name_;
- QString &var_;
+ QString& var_;
};
//------------------------------------------------------------------------
class BoolSetting: public VarSetting
{
- public:
- BoolSetting(const QString &name, bool &var): VarSetting(), name_(name), var_(var) { }
- void saveSetting(QSettings &st) {st.setValue(name_, var_); }
- void restoreSetting(QSettings &st) {if (st.contains(name_)) var_ = st.value(name_).toBool(); }
+public:
+ BoolSetting(const QString& name, bool& var): VarSetting(), name_(name), var_(var) { }
+ void saveSetting(QSettings& st)
+ {
+ st.setValue(name_, var_);
+ }
+ void restoreSetting(QSettings& st)
+ {
+ if (st.contains(name_)) {
+ var_ = st.value(name_).toBool();
+ }
+ }
- private:
+private:
QString name_;
- bool &var_;
+ bool& var_;
};
//------------------------------------------------------------------------
class DateTimeSetting: public VarSetting
{
- public:
- DateTimeSetting(const QString &name, QDateTime &var):VarSetting(), name_(name), var_(var) { }
- void saveSetting(QSettings &st) {st.setValue(name_, var_); }
- void restoreSetting(QSettings &st) {if (st.contains(name_)) var_ = st.value(name_).toDateTime(); }
+public:
+ DateTimeSetting(const QString& name, QDateTime& var):VarSetting(), name_(name), var_(var) { }
+ void saveSetting(QSettings& st)
+ {
+ st.setValue(name_, var_);
+ }
+ void restoreSetting(QSettings& st)
+ {
+ if (st.contains(name_)) {
+ var_ = st.value(name_).toDateTime();
+ }
+ }
- private:
+private:
QString name_;
- QDateTime &var_;
+ QDateTime& var_;
};
//------------------------------------------------------------------------
-class SettingGroup {
- public:
+class SettingGroup
+{
+public:
SettingGroup() {}
- ~SettingGroup() {
- for (int i=0; i< settingGroup_.size(); i++)
+ ~SettingGroup()
+ {
+ for (int i=0; i< settingGroup_.size(); i++) {
delete settingGroup_[i];
+ }
}
- void saveSettings(QSettings &st) {
- for (int i=0; i< settingGroup_.size(); i++)
+ void saveSettings(QSettings& st)
+ {
+ for (int i=0; i< settingGroup_.size(); i++) {
settingGroup_[i]->saveSetting(st);
+ }
}
- void restoreSettings(QSettings &st) {
- for (int i=0; i< settingGroup_.size(); i++)
+ void restoreSettings(QSettings& st)
+ {
+ for (int i=0; i< settingGroup_.size(); i++) {
settingGroup_[i]->restoreSetting(st);
+ }
}
- void addVarSetting(VarSetting *vs) {
+ void addVarSetting(VarSetting* vs)
+ {
settingGroup_ << vs;
}
- private:
- QList <VarSetting *> settingGroup_;
+private:
+ QList <VarSetting*> settingGroup_;
};
#endif
static const bool testing = false;
#endif
-UpgradeCheck::UpgradeCheck(QWidget *parent, QList<Format> &formatList,
+UpgradeCheck::UpgradeCheck(QWidget* parent, QList<Format>& formatList,
BabelData& bd) :
QObject(parent),
manager_(0),
}
UpgradeCheck::updateStatus UpgradeCheck::checkForUpgrade(
- const QString ¤tVersionIn,
- const QDateTime &lastCheckTime,
- bool allowBeta)
+ const QString& currentVersionIn,
+ const QDateTime& lastCheckTime,
+ bool allowBeta)
{
currentVersion_ = currentVersionIn;
currentVersion_.remove("GPSBabel Version ");
int rc = formatList_[i].getReadUseCount();
int wc = formatList_[i].getWriteUseCount();
QString formatName = formatList_[i].getName();
- if (rc)
+ if (rc) {
args += QString("&uc%1=rd/%2/%3").arg(j++).arg(formatName).arg(rc);
- if (wc)
+ }
+ if (wc) {
args += QString("&uc%1=wr/%2/%3").arg(j++).arg(formatName).arg(wc);
+ }
}
- if (j && babelData_.reportStatistics_)
+ if (j && babelData_.reportStatistics_) {
args += QString("&uc=%1").arg(j);
+ }
if (false && testing) {
qDebug() << "Posting " << args;
return UpgradeCheck::updateUnknown;
}
-QDateTime UpgradeCheck::getUpgradeWarningTime() {
+QDateTime UpgradeCheck::getUpgradeWarningTime()
+{
return upgradeWarningTime_;
}
-UpgradeCheck::updateStatus UpgradeCheck::getStatus() {
+UpgradeCheck::updateStatus UpgradeCheck::getStatus()
+{
return updateStatus_;
}
void UpgradeCheck::httpRequestFinished(QNetworkReply* reply)
{
- if (reply == 0 ) {
+ if (reply == 0) {
babelData_.upgradeErrors_++;
return;
} else if (reply != replyId_) {
QMessageBox::information(0, tr("HTTP"),
- tr("Unexpected reply."));
- } else if (reply->error() != QNetworkReply::NoError ) {
+ tr("Unexpected reply."));
+ } else if (reply->error() != QNetworkReply::NoError) {
babelData_.upgradeErrors_++;
QMessageBox::information(0, tr("HTTP"),
- tr("Download failed: %1.")
- .arg(reply->errorString()));
+ tr("Download failed: %1.")
+ .arg(reply->errorString()));
replyId_ = 0;
reply->deleteLater();
return;
if (statusCode != 200) {
QVariant reason = reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute);
QMessageBox::information(0, tr("HTTP"),
- tr("Download failed: %1: %2.")
- .arg(statusCode.toInt())
- .arg(reason.toString()));
+ tr("Download failed: %1: %2.")
+ .arg(statusCode.toInt())
+ .arg(reason.toString()));
replyId_ = 0;
reply->deleteLater();
return;
// This shouldn't ever be seen by a user.
if (!document.setContent(oresponse, &error_text, &line)) {
QMessageBox::critical(0, tr("Error"),
- tr("Invalid return data at line %1: %2.")
- .arg(line)
- .arg( error_text));
+ tr("Invalid return data at line %1: %2.")
+ .arg(line)
+ .arg(error_text));
babelData_.upgradeErrors_++;
replyId_ = 0;
reply->deleteLater();
QString response;
QString upgradeText;
- if (testing)
- currentVersion_ = "1.3.1"; // for testing
+ if (testing) {
+ currentVersion_ = "1.3.1"; // for testing
+ }
bool allowBeta = true; // TODO: come from prefs or current version...
upgradeText = upgrade.firstChildElement("overview").text();
// String compare, not a numeric one. Server will return "best first".
- if((updateVersion > currentVersion_) && updateCandidate) {
+ if ((updateVersion > currentVersion_) && updateCandidate) {
babelData_.upgradeOffers_++;
updateStatus_ = updateNeeded;
response = tr("A new version of GPSBabel is available.<br />"
- "Your version is %1 <br />"
- "The latest version is %2")
- .arg(currentVersion_, updateVersion);
+ "Your version is %1 <br />"
+ "The latest version is %2")
+ .arg(currentVersion_, updateVersion);
break;
}
}
information.setDetailedText(upgradeText);
switch (information.exec()) {
- case QMessageBox::Yes:
- // downloadUrl.addQueryItem("os", getOsName());
- QDesktopServices::openUrl(downloadUrl);
- babelData_.upgradeAccept_++;
- break;
- default: ;
- babelData_.upgradeDeclines_++;
+ case QMessageBox::Yes:
+ // downloadUrl.addQueryItem("os", getOsName());
+ QDesktopServices::openUrl(downloadUrl);
+ babelData_.upgradeAccept_++;
+ break;
+ default:
+ ;
+ babelData_.upgradeDeclines_++;
}
}
upgradeWarningTime_ = QDateTime(QDateTime::currentDateTime());
for (int i = 0; i < formatList_.size(); i++) {
- formatList_[i].zeroUseCounts();
+ formatList_[i].zeroUseCounts();
}
replyId_ = 0;
reply->deleteLater();
class QNetworkAccessManager;
class QNetworkReply;
-class UpgradeCheck : public QObject {
+class UpgradeCheck : public QObject
+{
Q_OBJECT
public:
- UpgradeCheck(QWidget *parent, QList<Format> &formatList, BabelData& bd);
+ UpgradeCheck(QWidget* parent, QList<Format>& formatList, BabelData& bd);
~UpgradeCheck();
typedef enum {
updateNeeded,
} updateStatus;
- UpgradeCheck::updateStatus checkForUpgrade(const QString &babelVersion,
- const QDateTime &lastCheckTime,
+ UpgradeCheck::updateStatus checkForUpgrade(const QString& babelVersion,
+ const QDateTime& lastCheckTime,
bool allowBeta);
QDateTime getUpgradeWarningTime(void);
UpgradeCheck::updateStatus getStatus(void);
QUrl upgradeUrl_;
QString latestVersion_;
QDateTime upgradeWarningTime_; // invalid time if this object never issued.
- QList<Format> &formatList_;
+ QList<Format>& formatList_;
updateStatus updateStatus_;
BabelData& babelData_;
#include "version_mismatch.h"
-VersionMismatch::VersionMismatch(QWidget *parent, const QString &ver1,
- const QString &ver2): QDialog(parent)
+VersionMismatch::VersionMismatch(QWidget* parent, const QString& ver1,
+ const QString& ver2): QDialog(parent)
{
ui_.setupUi(this);
#include "ui_version_mismatch.h"
-class VersionMismatch: public QDialog {
- public:
- VersionMismatch(QWidget *parent, const QString &ver1,
- const QString &ver2);
- bool neverAgain() { return ui_.neverAgain->isChecked(); }
+class VersionMismatch: public QDialog
+{
+public:
+ VersionMismatch(QWidget* parent, const QString& ver1,
+ const QString& ver2);
+ bool neverAgain()
+ {
+ return ui_.neverAgain->isChecked();
+ }
- private:
+private:
Ui_VersionMismatch ui_;
};